一、Activity生命周期
- 方法调用时机
- onCreate()
- Called when the activity is first created
页面第一次创建的时候调用
- Called when the activity is first created
- onDestroy()
- Called before the activity is destroyed
页面被销毁前调用
- Called before the activity is destroyed
- onStart()
- Called just before the activity becomes visible to the user
页面可见时调用
- Called just before the activity becomes visible to the user
- onStop()
- Called when the activity is no longer visible to the user
页面不可见时调用
- Called when the activity is no longer visible to the user
- onResume()
- Called just before the activity starts interacting with the user.
页面可以交互,获得焦点时调用
- Called just before the activity starts interacting with the user.
- onPause()
- Called when the system is about to start resuming another activity.
页面不可以交互,失去焦点时调用。即当系统调用了别的Activity时就会调用这个方法
- Called when the system is about to start resuming another activity.
- onCreate()
- 当界面横竖屏切换时,方法调用的顺序为onPause()、onStop()、onDestroy()、onCreate()、onStart()、onResume()
- 案例分析:
比如一个赛车的运用,马上要跑到终点,此时突然横竖屏切换了一下,导致他必须从头开始跑,这样给用户的体验特别差,为了改善用户的体验,我们通常使用以下办法:
在AndroidManifest.xml中,为activity添加一个 android:screenOrientation 属性,将横竖屏写死。其中portrait表示竖屏,landscape表示横屏。<activity android:name=".MainActivity" android:screenOrientation="portrait"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
二、任务栈
- 什么是任务?
在栈的概念中,我们开启一个Activity的时候叫做将一个Activity进栈了;而在Android运用中,我们开启一个Activity的时候叫做开启了一个任务。 - 任务栈的特点是什么?
- 打开一个Activity叫做进栈,关闭一个Activity叫做出栈
- 我们操作的Activity永远是在栈顶的Activity
- 任务栈是用来维护用户操作体验的
- 解释:一次只能操作一个Activity
- 任务栈清空了,应用程序就退出了
- 一般情况一个应用程序对应一个任务栈
三、Activity的四种启动模式
- 在哪里设置启动模式?
在AndroidManifest.xml文件中,每个activity下就可以通过 android:launchMode 设置当前activity的启动模式<activity android:name=".MainActivity" android:screenOrientation="landscape" android:launchMode="standard"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
- 四种启动模式
假设现在有两个界面,A界面和B界面,每个界面中都有两个按钮。A界面中两个按钮作用分别是跳转到当前界面和跳转到B界面;B界面中的两个按钮作用一样。其中A界面一直使用的standard模式,B界面使用四种不同的模式。- standard
图片表示:
规律总结:默认模式下的activity,无论当前是否处于栈顶位置,只要点击了创建按钮,就会在栈中创建一个新的实例 - singleTop
规律总结:singleTop模式下的activity,会检查当前activity是否处于栈顶。如果当前activity处于栈顶的位置,在栈中就不创建新的实例;如果当前activity不处于栈顶的位置,在栈中就创建新的实例
应用场景:浏览器书签 - singleTask
规律总结:singleTask模式下的activity,会检查栈中是否存在当前实例,如果不存在就会创建,如果存在就不会再次创建。当想使用该实例时,如果在栈中该实例上面有多个实例,就会将该实例上面的全部实例弹栈。
应用场景:浏览器的activity - singleInstance
规律总结:singleInstance模式下的activity,会自己创建新的任务栈,并且这个栈中只存在一个实例。两个任务栈的前后是有顺序的,当我们在A页面中点击按钮去到B页面时,此时B页面在A页面前面,弹栈时B页面中的实例弹栈完后,才是A页面中的实例弹栈;当我们在B页面中点击按钮去到A页面时,此时A页面在B页面前面,弹栈时A页面中的所有实例弹栈完后,才是B页面中的实例弹栈。
应用场景:来电页面
- standard