Android 中Activity的4种launchMode (验证)

来源:互联网 发布:java的soa架构 编辑:程序博客网 时间:2024/06/08 00:40
 
为了深刻理解,遂写此文 亦作为个人的验证(分析不同启动模式下的Activity生命周期)
此文的学习建立于已学习:http://blog.csdn.net/androideveloper/article/details/10264167
Pre: 跳转顺序 均是有startActivity(intent) 实现 无finish()
1.standard 此处不说,省略的时候就是用种启动模式,在同一个栈里面生成新的实例
onCreate -> onStart ->......->onDestory() 

2.singleTop 如果在任务的栈顶正好存在该Activity的实例, 就重用该实例,否者就会创建新的实例并放入栈顶(即使栈中已经存在该Activity实例,只要不在栈顶,都会创建实例
情况一:(本身位于栈顶 时 ,再次启动该Activity)
按钮不不断地启动自己startActivity(new Intent(ModeMainActivity.this, ModeMainActivity.class));

未点击按钮:

点击按钮后(不断点击也是这样)
由此可以看出,当ModeMode 位于栈顶时再启动这Activity,是不会实例化一个Activity,而是直接执行onPause() ->onNewIntent()->onResume() 红色部分是后来补充
原来在开发文档上有这么一句:
This is called for activities that set launchMode to "singleTop" in their package, or if a client used theandroid.content.Intent.FLAG_ACTIVITY_SINGLE_TOP flag when calling startActivity(android.content.Intent). In either case, when the activity is re-launched(onCreate->onStart()) while at the top of the activity stack instead of a new instance of the activity being started, onNewIntent() will be called on the existing instance with the Intent that was used to re-launch it.
An activity will always be paused before receiving a new intent, so you can count on onResume() being called after this method.
Note that getIntent() still returns the original Intent. You can use setIntent(android.content.Intent) to update it to this new Intent.

小总结:需要调用onNewIntent()的情况是:你要调用Activity已经存在了,不管在哪个栈里面

情况二(本身不位于栈顶时,再次启动该Activity)
Activity跳转顺序ModeMode --> B --> ModeMode 

由红色部分可以看到,当ModeMode 不位于栈顶时再启动这Activity,是会重新实例化一个Activity
(已同一个不会调用实例的onNewIntent())


3.singleTask   如果在栈中已经有该Activity的实例,就重用该实例(会调用实例的onNewIntent())。重用时,会让该实例回到栈顶,因此在它上面的实例将会被移除栈。如果栈中不存在该实例,将会创建新的实例放入栈中。
Activity跳转顺序ModeMode -->  ModeMode 



Activity跳转顺序ModeMode --> B --> ModeMode (大多数应用场景是这样的)
因此启动launchMode为singlTask的Activity 时,
OldActicity.onPause()->NewActivity.onNewIntent()-> NewActivity .onRestart()-> NewActivity .onStart()->NewActivity.onResume()

4.singleInstance 在一个新栈中创建该Activity实例,并让多个应用共享该栈中的该Activity实例。一旦该模式的Activity的实例存在于某个栈中,任何应用再激活改Activity时都会重用该栈中的实例,其效果相当于多个应用程序共享一个应用,不管谁激活该Activity都会进入同一个应用中。

Activity跳转顺序ModeMode -->  ModeMode (大多数极少应用场景是这样的)

Activity跳转顺序ModeMode --> B --> ModeMode (大多数应用场景是这样的)
启动顺序
onNewIntent()->onReStart()->onStart() ->onResume();