问题
So, I have 4 activities Activity Activity1
, Activity2
, Activity3
and Activity4
. I start from Activity1
then on some event I start Activity2
then on some event on Activity2
I start Activity3
as a new task as
public void onClick(View v) {
Intent intent = new Intent(Activity2.this, Activity3.class);
intent.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
Here Activity2
launchMode is decalared as singleTask.
Then I navigate from Activity3
to Activity4
When I start Activity2
from Activity4
I believe it should have backstack like
Task A
|Activity2|
|Activity1|
Task B
|Activity4|
|Activity3|
as shown in image below
but instead new instance of Activity2
is added to the current task as
Task B
|Activity2|
|Activity4|
|Activity3|
Task A
|Activity2|
|Activity1|
can someone please help me understand this?
回答1:
Android will not create a new task unless the taskAffinity
of the Activity
you are trying to launch is different from the taskAffinity
of the current task. taskAffinity
takes precendence over anything else.
If you really want to start a separate task, you'll need to adjust the taskAffinity
of the Activity3
like this:
<activity android:name=".Activity3"
android:taskAffinity=""/>
Also, even though Activity4
is declared with launchMode="singleTask"
, Android will not create a new task for it unless if has a different taskAffinity
from the other activities.
Please be aware that creating multiple tasks for the same application has a lot of side-effects. You should provide a uniqyue icon and a unique label for the root Activity
in each task, otherwise the user will be confused when he wants to return to your app (he won't be able to determine which of the various tasks is the correct one). Also, taskReparenting
can occur which will unexpectedly move activities from one task to another. This is all very complex stuff and most developers don't completely understand it and therefore get it wrong.
Also, the use of FLAG_ACTIVITY_MULTIPLE_TASK
is certainly wrong. The only type of application that needs to use this is a launcher. If you launch multiple tasks with the same Activity
in it, you will never be able to return to a specific one programatically, and will totally confuse your user. This is definitely not what you want.
In most cases you don't need multiple tasks, it usually causes more problems than it solves. Please explain why you think you need multiple tasks.
来源:https://stackoverflow.com/questions/35860779/singletask-launchmode-in-android-not-working