2

I have activities A -> B -> C -> D. How can I open the existing B from activity D clearing C and D? I would end up with A -> B. I don't want to recreate a new B.

3 Answers 3

5

I think you must use FLAG_ACTIVITY_CLEAR_TOP and FLAG_ACTIVITY_SINGLE_TOP.

According to the doc:

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.

The currently running instance of activity B in the above example will either receive the new intent you are starting here in its onNewIntent() method, or be itself finished and restarted with the new intent. If it has declared its launch mode to be "multiple" (the default) and you have not set FLAG_ACTIVITY_SINGLE_TOP in the same intent, then it will be finished and re-created; for all other launch modes or if FLAG_ACTIVITY_SINGLE_TOP is set then this Intent will be delivered to the current instance's onNewIntent().

1
  • This is the correct answer. When starting Ativity B from activity D, add these 2 flags. This will give you the behaviour you want. Commented Oct 16, 2014 at 10:50
0

You can declare you target activity's(Activity B in your situation) Mode of SingleTop in Manifest file like

<activity android:name="YourActivityName" android:launchMode="singleTop"></activity>

Then startActivity for navigating to this Activity will end C and D and wont start a new Activity B

2
  • It doesn't seem to be doing any difference.
    – awonderer
    Commented Oct 16, 2014 at 2:33
  • how about <activity android:name="YourActivityName" android:launchMode="singleTask"></activity> Commented Oct 16, 2014 at 3:02
0

Right after you finish dealing with C and D, you can just finish() the activities.

3
  • As the question says, I call B from D. I don't exit D and C to get to B.
    – awonderer
    Commented Oct 16, 2014 at 2:01
  • Oh sorry I miss-read in that case you just need to add a callback to Activity B and use resume the state of the activity Commented Oct 16, 2014 at 2:34
  • Can you elaborate on "add a callback to Activity B"? By "use resume the state of the activity", you mean onResume()?
    – awonderer
    Commented Oct 16, 2014 at 2:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.