Activity状态的保存

本文深入探讨了Android中Activity状态保存的多种方法,包括在onSaveInstanceState、onPause方法中保存瞬时与持久数据,以及使用SharedPreferences持久化数据。重点解析了onCreate方法如何复用保存的状态,确保应用在各种场景下能够恢复至用户离开时的状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于Activity状态的保存,简单的说有这么几种:

1、重写onSaveInstanceState(Bundle bundle)方法,在这里保存瞬间性数据

2、重写onPause()方法,在这里保存永久性数据

3、使用SharedPreferences,将状态数据存储到文件中


在文档中,有如下几处对onSaveInstanceState方法的描述:

{@link #onSaveInstanceState(Bundle)} is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle, to be later received in {@link #onCreate} if the activity needs to be re-created. 

在Activity被放置到后台状态之前onSaveInstanceState(Bundle)会被调用,并且允许你将任何的动态实例状态保存在给定的bundle中,如果这个activity需要重新创建的话,保存的状态会在onCreate中重新获得。


Note that it is important to save persistent data in {@link #onPause} instead of {@link #onSaveInstanceState} because the latter is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.

需要特别注意的是,持久性的数据需要在onPause中保存,而瞬间性的数据可以在onSaveInstance中保存,因为onSaveInstance并不是其生命周期中的一部分,因此将不一定在每种情况下都会被调用。


If its process needs to be killed, when the user navigates back to the activity (making it visible on the screen again), its {@link #onCreate} method will be called with the savedInstanceState it had previously supplied in {@link #onSaveInstanceState} so that it can restart itself in the same state as the user last left it.
如果它的进程需要被杀死,当用户回到这个activity时(确定它是在屏幕前是可见的),它的onCreate方法将被调用,由于它已经在之前的onSaveInstanceState中保存了,因此当在用户离开它之后,它可以以相同的状态重启它自己。


通过查看系统源码,在onCreate中,如果之前在Bundle中保存了相关的状态,再次调用onCreate时,是需要对saveInstanceState进行处理的,以便还原activity销毁前的状态。由于onSaveInstanceState方法不是生命周期方法,所以不一定会被调用,一般情况下,系统将activity销毁了,会调用这个方法,以保存当前的状态,而用户主动按下back键人为销毁的,是不会调用的。一般有以下几种情况,会调用:

1)当用户按下Home键的时候

2)长按Home键的,选择其他在运行的程序的时候

3)按下电源键的时候

4)从当前activity启动另一个activity的时候

5)屏幕方向发现旋转的时候,如横竖屏切换时(未进行相关处理)

当这几种情况发生了,需要再次返回到此activity的时候,可以重写相应的onRestoreInstanceState(Bundle savedInstanceState)方法,进行恢复数据。


参考博文:

             http://blog.youkuaiyun.com/niu_gao/article/details/7106911

             http://blog.youkuaiyun.com/huli870715/article/details/12238825




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值