Like many applications, my current project required me to add the ability for a user to log out from a settings page. In my case, I wanted to user to be sent to HomescreenActivity on logout. I did not want the user to be able to use the back button once they have logged out, because, well... they logged out.
By default the activity stack looked like this:
Homescreen -> Main -> Settings (logout) -> Homescreen
// For note, HomescreenActivity is setup in the
// manifest file as android:noHistory="true"
So pressing back would send me back to my Settings activity. Boo urns. Not what I wanted.
A little digging found that they key to controlling the back stack is by setting the correct intent flags:
// Called from my SettingsActivity
Intent i = new Intent(this, HomescreenActivity.class);
i.setFlags(i.FLAG_ACTIVITY_NEW_TASK | i.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i); // Launch the HomescreenActivity
finish(); // Close down the SettingsActivity
So what do these flags actually do?
From the Android Developer Docs:
FLAG_ACTIVITY_NEW_TASK
FLAG_ACTIVITY_CLEAR_TASK
When used in conjunction, these two flags will launch the desired activity as the root task, clearing all previously existing tasks in the stack, as we desired.
HomeScreen -> Main -> Settings (logout)
HomeScreen // New Task! (no back stack)
by Shayla Sawchenko