Reauthenticate on restart - Android

和自甴很熟 提交于 2019-12-11 02:19:29

问题


I need reauthenticate user credentials every time onRestart is called (usually this means the user has locked&unlocked the screen or put it on background and then returned to it).

So I did that:

@Override
protected void onRestart() {
    super.onRestart();

    Intent intent = new Intent(this, LoginActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setAction(LoginActivity.REAUTHENTICATE);
    startActivity(intent);
}

This works, the LoginActivity was shown, but when it finishes the onRestart of the first Activity is called again and the LoginActivity is opened again.

How can I handle that?


回答1:


Well, I used this to solve it:

    private static final int REAUTHENTICATE = 80;

    private boolean authenticated;

    @Override
    public void onRestart() {
        if(authenticated)
            return;

        Intent intent = new Intent(this, LoginActivity.class);
        intent.setAction(LoginActivity.REAUTHENTICATE);
        startActivityForResult(intent, REAUTHENTICATE);
    }

    @Override
    public void onStop() {
        authenticated = false;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == REAUTHENTICATE)
            authenticated = true;
    }

Well, this it no what I expected but works, I hope someone find a better solution. Cause onRestart keep getting called after onActivityResult.




回答2:


Until got a good solution/suggestion from any one can try this .

1- Put a boolean variable in shared pref named AuthentacationNeeded
2- get that in OnRestart with default value true 
3-if value is true then only startActivity
4- put that variable true in onpuase 

in Login activity 
4-   put that variable false Before finish()


来源:https://stackoverflow.com/questions/11144155/reauthenticate-on-restart-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!