android:launchMode
描述Activity 如何启动的指令,结合 Intent
的FLAG_ACTIVITY_*
来确定Activity
如何的启动意图。
它们分别是:
-standard
(默认)
-singleTop
-singleTask
-singleInstance
模式主要分为2组:
standard
与singleTop
。
被标记为standard
与singleTop
的Activity
可以被多次实例化,实例可以属于多个Task
,并位于多个ActivityStack
中。通常,调用startActivity()
将之装载到Task
中。需要注意的是,当Intent
中含有FLAG_ACTIVITY_NEW_TASK
指令时,选中哪一个Task
需要参考taskAffinity
属性。
相比之下,被标记为singleTask
与singleInstance
的Activity
只能启动一个 task。它们总是位于ActivityStack
中的根节点。 此外,设备通常一次只能持有一个Activity
实例,仅允许一个task。
standard
与singleTop
模式的两者不同之处在于:
- 每当一个新的
Intent
标记standard
模式,一个新的Activity
的实例将会被创建。每个实例持有对应的唯一的Intent
实例。 singleTop
模式也类似。但是,如果目标 task 已经持有已存在的Activity
的实例并且处于栈顶,则该实例会接收到本次新的Intent
(表现框架调用onNewIntent()
方法),从而避免创建新的Activity
的实例。在其他情况下,如果一个已存在于栈中的Activity
实例但并不是处于栈顶。或一个处于栈顶但并不是目标task ,则依然会创建实例会推送 Activity的栈中。
Similarly, if you navigate up to an activity on the current stack, the behavior is determined by the parent activity’s launch mode. If the parent activity has launch mode singleTop
(or the up
intent contains FLAG_ACTIVITY_CLEAR_TOP
), the parent is brought to the top of the stack, and its state is preserved. The navigation intent is received by the parent activity’s onNewIntent()
method. If the parent activity has launch mode standard
(and the up
intent does not contain FLAG_ACTIVITY_CLEAR_TOP
), the current activity and its parent are both popped off the stack, and a new instance of the parent activity is created to receive the navigation intent.
singleTask
与singleInstance
。
singleTask
与singleInstance
模式的两者不同之处在于:
singleTask
的 activity 允许(特指标记为standard
与singleTop
) 的activities,并入它的 task 中且它永远是处在 task 中的根节点。singleInstance
的 activity 不允许其它 activities 并入它的 task 中(意味着 task 中有且仅有一个 activity )。从它启动新的 activity,则需要分配不同的 task,如分配Intent.FLAG_ACTIVITY_NEW_TASK
。
Use Cases | Launch Mode | Multiple Instance? | Comments |
---|---|---|---|
正常 | standard | 是 | Default. The system always creates a new instance of the activity in the target task and routes the intent to it. |
正常 | singleTop | 有条件的 | If an instance of the activity already exists at the top of the target task, the system routes the intent to that instance through a call to its onNewIntent() method, rather than creating a new instance of the activity. |
特殊 | singleTask | 不 | The system creates the activity at the root of a new task and routes the intent to it. However, if an instance of the activity already exists, the system routes the intent to existing instance through a call to its onNewIntent() method, rather than creating a new one. |
特殊 | singleInstance | 不 | Same as “singleTask”, except that the system doesn’t launch any other activities into the task holding the instance. The activity is always the single and only member of its task. |
最后总结一下:
standard
默认模式,适合绝大多数的情况。SingleTop
常用有效模式,适合部分情况。singleTask
与singleInstance
,不适合于大多数情况。因为它们的交互模型不太亲近用户的行为模型,有别于其他大多数的应用程序。- 无论选择何种模式,使用
Back Button
确保它的可用性与正确性。
更多资料,看看Tasks and Back Stack文档。