學習作業系統時,我們知道CUP處理事務的時候有個中斷機制,以便進行事務的切換,中斷處理的過程: 1)喚醒被阻塞的驅動(程式)進程;2)保護被中斷的CPU環境;3)轉入響應的裝置處理常式;4)中斷處理;5)恢複被中斷的進程。
在Android當中也有類似的概念,在activity的生命週期中
,當處於onPause() ,onStop() ,onDestroy() 三種狀態時程式可能會被Android 系統kill掉,這時如果之前未進行保護操作把資料儲存的話就會造成使用者在程式當中的資料或者修改丟失。也就是這裡要講的“現場保護”,我們希望當下次在運行程式時,上一次的資料還能恢複。
Android提供了 onSaveInstanceState(Bundle) 方法,它可以在程式被onStop()直前被調用,但不能保證是否在onPause()之前。(原話是這樣的:If called, this method will occur before onStop(). There are no guarantees about whether it will occur before or after onPause(). )
這個方法的作用官方是這麼表述的:Called to retrieve per-instance state from an activity before being killed so that the state can be restored in onCreate(Bundle) or onRestoreInstanceState(Bundle)(the Bundle populated by this method will be passed to both).翻成中文大概就是在一個activity被殺死之前被調用,可以儲存它的一些狀態資料,存在一個bundle對象中,這個對象可以在下次啟動程式調用onCreate(Bundle)或onRestoreInstanceState(Bundle)時作為傳遞的參數,這也就是為什麼我們每一個activity重寫的onCreate方法都有這麼一段:
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}。
onSaveInstanceState(Bundle) 裡面的這個Bundle對象和onCreate中的所指相同對象。
那到底什麼時候會調用這個方法,其實並不是在activity被destroy就一定調用。當使用者自己通過正常手段,不如導覽按鈕“返回鍵”退出程式時,並不會調用onSaveInstanceState(Bundle),因為這個沒必要。(Note: There's no guarantee that onSaveInstanceState() will be called before your activity is destroyed, because there are cases in which it won't be necessary to save the state (such as when the user leaves your activity using the BACK key, because the user is explicitly closing the activity). If the method is called, it is always called before onStop() and possibly before onPause(). )
那麼什麼情況下沒有必要調用呢?下面的兩幅對比圖比較清晰的說明了(the two ways in which an activity returns to user focus with its state intact: either the activity is stopped, then resumed and the activity state remains intact (left), or the activity is destroyed, then recreated and the activity must restore the previous activity state (right). )
關於對onSaveInstanceState(Bundle)的理解在官方說明中非常詳盡,這裡僅僅是我在學的過程中的部分理解。