Activity backstack FLAG_ACTIVITY_NEW_TASK

271 Views Asked by At

I a bit confused with the documentation for launch modes. Specifically the doc mentions:

Activities in the stack are never rearranged, only pushed and popped from the stack

But later in the section for FLAG_ACTIVITY_NEW_TASK it is mentioned:

If a task is already running for the activity you are now starting, that task is brought to the foreground with its last state restored and the activity receives the new intent in onNewIntent().

There is no clarification here if that the activity is on the top of the stack and this makes me wonder how is that possible without rearranging the stack.
So for instance if we have activities A and B and A launches B:

A<-B

Now if B launches A with FLAG_ACTIVITY_NEW_TASK would that mean that it would resume the previous instance? I.e. the back stack will be:

B <- A
or would we have:
A <- B <- A

2

There are 2 best solutions below

5
On

Assuming that both activities have the same taskAffinity, you have the following scenario:

If A launches B, you have this:

A->B (A is the root Activity and B is on top of the stack and shown to the user)

Now, if B launches A, you have this:

A->B->A' (A is the root, B is on top of A, and A' (another instance of Activity A is on top of B and is shown to the user. onNewIntent() is not called in this case.

This assumes that you do NOT use FLAG_ACTIVITY_CLEAR_TOP when launching A again, and also assumes that finish() has not been called by either A or B.

Adding FLAG_ACTIVITY_NEW_TASK has absolutely no effect on this at all.


NOTE: Also, the statement in the documentation that "Activites are never rearranged" is actually false. I'm pretty sure I opened an issue about this at Google about 3 times, but... Anyway, if you use FLAG_ACTIVITY_REORDER_TO_FRONT this will move an Activity from anywhere in the stack to the top of the stack.


Another NOTE: Also, onNewIntent() is only ever called on the Activity that is on the top of the stack (ie: the one that the user sees).

0
On

all the destination added to the backstack will be popped till the one that you're requesting to. So in your case the result should be only activity A with the onNewIntent() method call. Refer to this article with examples about task and backstack