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)的理解在官方说明中非常详尽,这里仅仅是我在学的过程中的部分理解。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?