當裝置旋轉時android生命週期方法的呼叫順序

SpiritSea發表於2016-01-05

特別注意onSaveInstanceState並不是生命週期方法

當裝置旋轉時,通過Log可以看出:

裝置銷燬Activity例項:

01-05 20:07:11.289 7860-7860/? D/QuizActivity: onPause(Bundle) called

01-05 20:07:11.290 7860-7860/? I/QuizActivity: onSaveInstanceState

01-05 20:07:11.290 7860-7860/? D/QuizActivity: onStop(Bundle) called

01-05 20:07:11.317 7860-7860/? D/QuizActivity: onDestroy(Bundle) called

重建Activity例項:

01-05 20:07:11.353 7860-7860/? D/QuizActivity: onCreate(Bundle) called

01-05 20:07:11.373 7860-7860/? D/QuizActivity: onStart(Bundle) called

01-05 20:07:11.377 7860-7860/? D/QuizActivity: onResume(Bundle)called


*繼續深入

當我把setting->developer option->Don't keep activities開啟後再進行測試:

  1. 點選Back鍵

    01-05 21:15:38.946 13590-13590/? D/QuizActivity: onPause(Bundle) called

    01-05 21:15:39.878 13590-13590/? D/QuizActivity: onStop(Bundle) called

    01-05 21:15:39.886 13590-13590/? D/QuizActivity: onDestroy(Bundle) called

    發現onSaveInstanceState並沒有被呼叫

  2. 點選Home鍵

    01-05 21:17:43.975 13590-13590/? D/QuizActivity: onPause(Bundle) called

    01-05 21:17:44.723 13590-13590/? I/QuizActivity: onSaveInstanceState

    01-05 21:17:44.723 13590-13590/? D/QuizActivity: onStop(Bundle) called

    01-05 21:17:44.741 13590-13590/? D/QuizActivity: onDestroy(Bundle) called

當把Don't keep activities選項關閉後再進行上述相同測試發現:

唯一不同的是點選Home鍵依次執行:

01-05 21:17:43.975 13590-13590/? D/QuizActivity: onPause(Bundle) called

01-05 21:17:44.723 13590-13590/? I/QuizActivity: onSaveInstanceState

01-05 21:17:44.723 13590-13590/? D/QuizActivity: onStop(Bundle) called

Activity沒有被Destroy

而點選Back鍵,Activity都會被銷燬(也不會儲存activity的狀態,即:不呼叫onSaveInstanceState)。可以理解為Back鍵相當於通知系統“使用者不再需要當前的Activity”。

內容參考:Android程式設計權威指南

相關文章