Android程序的“现场保护”
学习操作系统时,我们知道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)的理解在官方说明中非常详尽,这里仅仅是我在学的过程中的部分理解。