onCreate
→ onStart
→ onResume
→ onPause
→ onStop
→ onDestroy
1. Activity 切换(A → B)
onPause()
onCreate()
→ onStart()
→ onResume()
onStop()
2. 按下 Home 键
onPause()
→ onSaveInstanceState()
(可能)→ onStop()
3. 从桌面图标返回应用
onRestart()
→ onStart()
→ onResume()
onCreate()
→ onStart()
→ onRestoreInstanceState()
(可选)→ onResume()
4. 按下返回键退出 Activity
onPause()
→ onStop()
→ onDestroy()
5. 屏幕旋转(配置变更)
onPause()
→ onSaveInstanceState()
→ onStop()
→ onDestroy()
onCreate()
→ onStart()
→ onRestoreInstanceState()
→ onResume()
1. onSaveInstanceState(Bundle outState)
触发时机:在 Activity 有可能被销毁且后续会重建的情况下(如屏幕旋转、按 Home 后被系统杀死、配置变更)。
作用:用于保存临时 UI 状态,例如:
调用时机依赖于目标 SDK 版本:
onSaveInstanceState()
在 onStop()
之后 被调用。onSaveInstanceState()
在 onStop()
之前 被调用,且与 onPause()
之间的顺序不保证稳定。引用官方文档说明:
If called, this method will occur after onStop() for applications targeting platforms starting with Build.VERSION_CODES.P. For applications targeting earlier platform versions this method will occur before onStop() and there are no guarantees about whether it will occur before or after onPause().
2. onRestoreInstanceState(Bundle savedInstanceState)
onCreate()
中的 savedInstanceState != null
且确实调用了 onSaveInstanceState()
的情况下。onStart()
之前自动调用。onCreate()
中读取 savedInstanceState
的逻辑互补,但更适合专门处理 UI 状态的恢复操作。onCreate()
中判断 savedInstanceState != null
并进行恢复,也可以选择分开处理:保存放在 onSaveInstanceState()
,恢复专门放在 onRestoreInstanceState()
。ViewModel
、SavedStateHandle
、DataStore
或数据库。