Reauthenticate on restart - Android

2019-07-19 10:37发布

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?

2条回答
乱世女痞
2楼-- · 2019-07-19 10:59

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.

查看更多
劫难
3楼-- · 2019-07-19 11:08

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()
查看更多
登录 后发表回答