How to Control Android back stack

Vlad picture Vlad · Jan 3, 2013 · Viewed 30.1k times · Source

Lets say I have

A->B->C->D->E

In android back stack. I want to be able to get back to one of the following:

A->B->C
A->B
A

How can I achieve this? Hopefully without forcing back button clicks.

Answer

varevarao picture varevarao · Jan 3, 2013

Using the image and information from the official developers page on Android tasks and back stack you can see that of all other ways to launch an Activity you can ensure such behavior only using the FLAG_ACTIVITY_CLEAR_TOP in your Intent flags.

Your regular back button proceeds as:

enter image description here

But when you specify this flag, you get a behavior like you need, as given by an example at this source:

consider a task consisting of the activities: A, B, C, D. If D calls startActivity() with an Intent that resolves to the component of activity B, then C and D will be finished and B receive the given Intent, resulting in the stack now being: A, B.