學習操作系統時,我們知道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)的理解在官方說明中非常詳盡,這里僅僅是我在學的過程中的部分理解。
