Activity有四种加载模式:
- standard
- singleTop
- singleTask
- singleInstance
standard
首先说standard模式,也就是默认模式,不需要配置launchMode
singleTop
singleTop和standard模式,都会将intent发送新的实例(后两种模式不发送到新的实例,如果已经有了的话)。不过,singleTop要求如果创建intent的时候栈顶已经有要创建的Activity的实例,则将intent发送给该实例,而不发送给新的实例。
还是用刚才的示例,只需将launchMode改为singleTop,就能看到区别。
运行的时候会发现,按多少遍按钮,都是相同的ActiA实例,因为该实例在栈顶,因此不会创建新的实例。如果回退,将退出应用。
singleTop模式,可用来解决栈顶多个重复相同的Activity的问题。
如果是A Activity跳转到B Activity,再跳转到A Activity,行为就和standard一样了,会在B Activity跳转到A Activity的时候创建A Activity的新实例,因为当时的栈顶不是A Activity实例
Use Cases | Launch Mode | Multiple Instances? | Comments |
---|---|---|---|
Normal launches for most activities | "standard " | Yes | Default. The system always creates a new instance of the activity in the target task and routes the intent to it. |
"singleTop " | Conditionally | 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. | |
Specialized launches (not recommended for general use) | "singleTask " | No | 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 " | No | 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. |
“singleInstance”独占一个task,其它activity不能存在那个task里;如果它启动了一个新的activity,不管新的activity的launch mode 如何,新的activity都将会到别的task里运行(如同加了FLAG_ACTIVITY_NEW_TASK参数)。
而另外三种模式,则可以和其它activity共存。
startard:标准方式,启动一个Activity就创建一个实例。
singleTop:当Activity栈最顶层的A1启动另一个A1时,不会启动新实例。
singleTask:在Task范围内只产生一个实例。
singleInstance:在全局范围内只有一个,即使在不同apk中调用