Search code examples
androidandroid-activitystack

Clear android activity stack starting a new activity


I have an application and every new created activity will start an async task to validate the user session. If the session is valid, the application flows continues. If not, the whole activity stack must be cleared and there should be only the login activity. This activity has a "no history" flag so it is never kept in the stack.

I've been trying some solutions provided here: Android: Clear Activity Stack but with no success.

This must works on the lowest android possible, being the least 2.2

Thanks!


Solution

  • I keep my login Activity on the stack. In the onResume() of the login Activity, I check to see if the user has login credentials and, if so, call startActivity for the next screen presented after login. The user does not see the login screen in this case.

    When the user presses the logout button, I clear the user's credentials and then this clears the stack all the way back to the login screen:

        Intent intentLaunchLogin = new Intent(this, ActivityLogin.class);
        intentLaunchLogin.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intentLaunchLogin);
    

    Also, if the user is on the screen presented after the login and they press the 'back' button, I don't want them to go to the login Activity. This code will send the user to the Home screen as would be expected:

    moveTaskToBack(true);