Clearing an activity stack
Sometimes you may want to start a new activity while removing previous activities from the back stack, so the back button doesn’t take you back to them. One example of this might be starting an app on the Login activity, taking you through to the Main activity of your application, but on logging out you want to be directed back to Login without a chance to go back. In a case like that you can set the
FLAG_ACTIVITY_CLEAR_TOP flag for the intent, meaning if the activity being launched is already running in the current task (LoginActivity), then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.
Intent intent = new Intent(getApplicationContext(), LoginActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent);
It’s also possible to use the flags
FLAG_ACTIVITY_NEW_TASK along with
FLAG_ACTIVITY_CLEAR_TASK if you want to clear all Activities on the back stack:
Intent intent = new Intent(getApplicationContext(), LoginActivity.class); // Closing all the Activities, clear the back stack. intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent);