对于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)方法,进行恢复数据。