How to restore fragment back stack with in an activity (After application is killed in background)

Arun C picture Arun C · Feb 19, 2016 · Viewed 9.1k times · Source

In an Android app-

Say I am in an Activity - MyActivity which holds one Fragment at a time.

First I loaded Fragment A to it (With no tags I added it to back stack of the FragmentManager)

Then at some point I loaded Fragment B (Again with no tags I added it to back stack of the FragmentManager)

Then at some point i loaded Fragment C (Again with no tags I added it to back stack of the FragmentManager)

I am using popBackStack() to enable back button behavior so whenever I press back from Fragment C the flow is like:

Fragment C -> Fragment B -> Fragment A -> Close MyActivity..

Everything is perfect :-)

But if I am in Fragment C and the app gets killed in background (I used "do not keep activity flag" from Settings)

and come back online Fragment C is loaded in MyActivity

but the FragmentManager's back stack contains only Fragment C..

The Back button is messing it up

Fragment C -> Close MyActivity..

Why is it so?

How to properly restore FragmentManager's back stack within an Activity?

Answer

shredder picture shredder · Feb 29, 2016

Try using alwaysRetainTaskState on your root activity. Android automatically clears the Activity backstack because it assumes that it has been a long time since you used the app and that the user wants to start again from the start.

 <activity android:alwaysRetainTaskState="true"/>

This setting will prevent that behaviour and it may follow that the behaviour is inherited by the Fragment Manager.