Clearing an activity stack

suggest change

To open an activity and remove the ones above it, so Back does not return to them, set FLAG_ACTIVITY_CLEAR_TOP. A typical case is logout: the task was Login, then Main, and logout should return to Login. If LoginActivity is already in the current task, the activities above it are finished. With the default standard launch mode, also set FLAG_ACTIVITY_SINGLE_TOP when the existing instance should receive the Intent in onNewIntent. Without that flag, the existing instance is finished and a new one is created.

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);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents