Activity 的生命週期圖
以下整理幾種狀況來看看不同動作的狀態
在寫程式時,要在哪個狀態下把功能開啟或收回
需要針對不同需求好好考量
1.正常狀況的生命週期
(Activity launched) -> onCreate -> onStart -> onResume -> (Activity Running) -> onPause -> onStop -> onDestory -> (Activity Shutdown)
2.螢幕關閉時會停在 onPause
(Activity Running) -> (screen close) -> onSaveInstanceState -> onPause -> (screen open) -> onResume -> (unlock) -> (Activity Running)
3.Activity 開啟另一個 Activity 的切換
(Activity1 Running) -> (start Activity2) -> (Activity1)onSaveInstanceState -> (Activity1)onPause -> (Activity2)onCreate -> (Activity2)onStart -> (Activity2)onResume -> (Activity2 Running) -> (Activity1)onStop -> (Back) -> (Activity2)onPause -> (Activity1)onRestart -> (Activity1)onStart -> (Activity1)onResume -> (Activity1 Running) -> (Activity2)onStop -> (Activity2)onDestory
原 Activity 會進入 onPause 狀態
然後待開啟的 Activity 開始 onCreate
等到開啟完成後原 Activity 才會進入 onStop 狀態
而在新開的 Activity 按 Back 鍵時,它會先進入 onPause
等原 Activity 回復運行
新開的 Activity 才會 onStop 和 onDestroy
4.旋轉版面
(Activity Running) -> (rotate) -> onSaveInstanceState -> onPause -> onStop -> onRetainNonConfigurationInstance -> onDestory -> onCreate -> onStart -> onRestoreInstance -> onResume -> (Activity Running)
狀態的儲存與回覆靠的是存在 Bundle 裡的資訊(SparseArray)
( onCreate , onSaveInstanceState, onRestoreInstance 這三者都會傳入 Bundle 參數)
如果有一個以上 Activity,只會影響到最前面的
5. Activity Stack
(Activity1 Running) -> (start Activity2) -> (過程省略) -> (Activity2 Running) -> (Activity1)onStop -> (Home) -> (Activity2)onSaveInstanceState -> (Activity2)onPause -> (Activity2)onStop -> (stop app process) -> (relaunch app) -> (Activity2)onCreate -> (Activity2)onStart -> (Activity2)onRestoreInstance -> (Activity2)onResume -> (Activity2 Running)
app 被殺掉後再回復時,只會 create 在 Activity State 最上面的 Activity
6.Application & Activity
(launch app) -> (Application)onCreate -> (Activity1)onCreate -> (省略) -> (Activity1 running) -> (rotate) -> (Application)onConfigurationChanged -> (Activity1)onSaveInstanceState -> (Activity1)onPause -> (省略) -> (Activity1)onCreate -> (省略) -> (Activity1)onRestoreInstance -> (Activity1)onResume -> (Activity1 Running)
Application 類在 app 啟動時會先 on Create
所以可把一些通用 static 常數或一些初始化的東西放在這裡
它的生命週期跟這個 app 的 process 一樣長
旋轉手機時雖然只有最上方可視的 Activity 會受影響
但 Application 類也會發出事件 onConfigurationChanged
除了 onCreate 跟 onConfigurationChanged 之外
Application 類還有 onTerminate 跟 onLowMemory 事件
最後來看看系統回收 process 的優先順序:(依重要性排列)
1. Foreground process
-Active Activity
-Active Service
-Active BroadcastReceiver
2. Visible process
-Activity at onPause() stage
-----------------------------(以上被系統回收的機率極小)
3. Service process
-----------------------------(以上被系統回收的機率小)
4. Background process
-Activity at onStop() stage
5. Empty process
-----------------------------(以上被系統回收的機率大)
沒有留言:
張貼留言