So I would like to know how I can manage the back stack for activities that are launched from the NavigationDrawer. If I launch various activities via the NavigationDrawer by default Android will add them to the back stack and it would cause back button hell as user.
I imagine this should be a common problem so there must be a adequate solution.
But I need a solution to cater for the following 3 requirements.
I have 2 items in the navigation drawer (Activity1 and Activity2) which each launch different Activites. If I open the items via the navigation drawer a number of times when I press back I wish to go back to the initial starting activity and if I press back again I wish to exit the app
I launch Activity 1 from Nav then I launch Activity 2 and from within this activity I launch a new activity SubActivity. Now when I press back I would expect to be taken back to Activity 2 and then if I press back again I would expect to be taken to the initial Activity (not Activity 1), and then pressing back again would exit.
Same as above but actually the initial Activity is dynamic. So the landing Activity is defined by a user setting about what their first screen shall be.
As you can see I can not use NO_HISTORY flag because of (requirement 2)and I cant hardcode the parent of the Activities because of (requirement 3).
So other than overriding the back button is there any other way that i can manipulate the back stack ?
Launch mode will not help. The answers lies in using TaskStackBuilder, its a very powerful api that allows you to define exactly what is to go into the backstack of the activity that you are about to launch. Here is how to use it.
Intent activityInBackstack = new Intent(this, ActivityA.class); Intent activityToBeLaunched = new Intent(this, ActivityB.class); TaskStackBuilder builder = TaskStackBuilder.create(this); builder.addNextIntent(activityInBackstack); builder.addNextIntent(activityToBeLaunched); builder.startActivities();
So now if you are in ActivityB and you press back button you will always go to ActivityA. Pressing back on ActivityA would exit the app.