Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Control Android back stack

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.

like image 836
Vlad Avatar asked Jan 03 '13 16:01

Vlad


People also ask

What is Android back stack?

A task is a collection of activities that users interact with when trying to do something in your app. These activities are arranged in a stack—the back stack—in the order in which each activity is opened. For example, an email app might have one activity to show a list of new messages.

How does the Android back button work?

When you press the Back button, the current destination is popped off the top of the back stack, and you then navigate to the previous destination. The Up button appears in the app bar at the top of the screen. Within your app's task, the Up and Back buttons behave identically.

What is Android Launchmode?

This is the default launch mode of activity (If not specified). It launches a new instance of an activity in the task from which it was launched. Numerous instances of the activity can be generated, and multiple instances of the activity can be assigned to the same or separate tasks.


2 Answers

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.

like image 182
varevarao Avatar answered Oct 05 '22 02:10

varevarao


Use FLAG_ACTIVITY_CLEAR_TOP flag.

Intent a = new Intent(this, A.class);
a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(a);
like image 31
hkutluay Avatar answered Oct 05 '22 04:10

hkutluay