Question

The functionality I want to model in my Android app is, that if the user does login, he gets forwarded to the main menu (MainMenuActivity). From here and everywhere else where I provide a button for it in the app, he must be able to logout, which should send him back to the login screen (LoginActivity) and finish all the activities above on the stack. I achieve this by not destroying the LoginActivity after a login and at logout calling:

    Intent intent = new Intent(this, LoginActivity.class);
    // Clean up all other activities.
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    startActivity(intent);

Also I want that the user can not go back with the backbutton form the main menu to the loginscreen. So I did overwrite the method onBackPressed() in my MainMenuActivity. Instead I want that when the user is pressing the backbutton from the main menu, the app does terminate (just like its the last activity on the stack). How can I achieve this?

I did read about several other approaches, for example finishing the LoginActivity after the login was performed and then later do it like described here:

https://stackoverflow.com/a/3008684/1332314

But I'm not quite sure if this is a proper solution, just read the comments below the post.

Was it helpful?

Solution

use this flag when you move to MainMenuActivity:

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_CLEAR_TASK);

this will delete all the previous activity and if you press back app will be closed.

Now in case of logout button do the same thing when you move to LoginActivity same flag will now make LoginActivity as the only activity on the stack and on back app will be closed.

OTHER TIPS

Apparently I did find a solution to my problem. I just start the MainMenuActivity from the LoginActivity like this:

private void continueToMainMenu() {
    Intent intent = new Intent(this, MainMenuActivity.class);
    startActivityForResult(intent, 0);
}

Then, when the user presses the backbutton in the main menu, this overwritten function gets called:

public void onBackPressed() {
    setResult(LoginActivity.ACTION_QUIT);
    finish();
}

This will at first set a resultcode for the LoginScreen and then finish the MainMenuActivity. Then the LoginActivity does terminate receiving this particular resultcode, which I implemented like this:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode == LoginActivity.ACTION_QUIT)
    {
        finish();
    }
}

Doing it this way will ensure not to touch too deep into the activity lifecycles, all the callbacks to clean up will still be called and it should not open any security leaks.

Hope this helps if anyone else will bump into the same issue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top