Clearing an activity stack
suggest changeTo 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);
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents