Search code examples
androidandroid-intentandroid-activitylaunchmode

Launching activity from a singleinstance activity


I have 3 activities:

A, B , C

A has singleInstance launchMode.

A is the main activity, which launches B, B launches C, then I press the home button and open the app again.

A is opened, but when A tries to launch B, the existing stack is opened instead (returns to existing C)

Is this the expected behaviour?


Solution

  • If A is singleInstance, when A launches B, Android automatically adds FLAG_ACTIVITY_NEW_INSTANCE to the Intent (because A is singleInstance) and because of that it creates a new task with B at the root of the task. Then B launches C. Andriod launches C into the same task as B (this is the normal behaviour). So now you have 2 tasks: One with just A in it, and another which has B at the root, with C on top of that.

    Now you go back to the task containing A. When A launches B again, Android again adds FLAG_ACTIVITY_NEW_TASK to the Intent). Then, because FLAG_ACTIVITY_NEW_TASK is set, Android looks for an existing task that has B at the root. Since it finds one, it simple brings that task to the foreground in whatever state the task was in when that task went to the background. This is the normal and expected behaviour.

    NOTE: This is just one more reason NOT to use the special launch modes singleInstance and singleTask, because they have lots of nasty, undocumented, misunderstood side-effects.