標籤:android onsaveinstancestate onpause
onPause在Activity部分不可見的時候被調用,onSaveInstanceState在需要空出記憶體給當前Activity的時候執行。onSaveInstanceState有時候在onPause()運行前調用,有時候不(Pre-HONEYCOMB 版本前可能先調用onSaveInstanceState,之後onPause先調用)。Android Activity的詳細文檔在這裡。
再來看函數名,onSaveInstanceState,儲存的是Activity執行個體的狀態,強調Instance。onPause是生命週期的一部分,屬於正常的生老病死,沒什麼好解釋的,如果想加強記憶,可以看gasolin 的這篇https://code.google.com/p/androidbmi/wiki/LifeCycle。
預設的Activity onSaveInstanceState方法會做儲存帶id的view(Edittext這樣的控制項)的狀態。我對view不甚瞭解,原文是:
“The default implementation takes care of most of the UI per-instance state for you by callingonSaveInstanceState() on each view in the hierarchy that has an id, and by saving the id of the currently focused view (all of which is restored by the default implementation ofonRestoreInstanceState(Bundle)). If you override this method to save additional information not captured by each individual view, you will likely want to call through to the default implementation, otherwise be prepared to save all of the state of each view yourself. ”
什麼時候要重載onSaveInstanceState呢?絕大部分時候。但是因為預設的Activity onSaveInstanceState函數做了儲存view狀態的工作,所以重載的機會大大減少,變成如果你用了其它控制項的時候(例如你自己做的畫圖控制項,或者需要儲存activity的一些屬性值,如session id), 需要重載onSaveInstanceState。否則你的activity被回收後重新進入,圖形資料全沒了。
還有一個問題:什麼時候需要重載onPause呢?釋放資源的時候,這個很好理解;還有,你想在正常退出程式儲存資料時。第二個重載原因有點違反直覺,要我給app例子的話我能想到“簡訊”、“記事本”,還有Android範例程式碼裡的notepad。手機的操作大部分都是按返回鍵或者Home鍵,你分不清使用者是要關閉你的程式還是切到其它app裡,所以不管三七二十一,資料統統在onPause裡存下來。當然,如果你要做得夠細,需要在onDestroy裡詢問使用者要不要儲存,但有時onDestroy根本得不到機會執行activity就被kill掉了。如果再考慮調用其它activity時原來activity的onDestroy會被調用,就更拎不清。
onSaveInstanceState儲存內容的方式和onPause不一樣。onSaveInstanceState是存在系統緩衝裡,onPause寫persistent data。為什麼要這樣呢? 因為Instance data只是在重新create activity時用,換句話說只是對app編寫者有用,而onPause存下來的是對app使用者有用的資料。
最後,讓我們來想想Android的重啟提示。如果你的app被後台kill掉了,onSaveInstanceState非常及時的把資料存在了Bundle裡,但是使用者選擇了關機,Bundle裡的資料還在嗎?
Android onPause和onSaveInstanceState的區別