Android onPause和onSaveInstanceState的区别

来源:互联网 发布:微信 视频编辑软件知乎 编辑:程序博客网 时间:2024/05/02 04:59

onPause在Activity部分不可见的时候被调用,onSaveInstanceState在需要空出内存给当前Activity的时候执行。onSaveInstanceState有时候在onPause()运行前调用,有时候不(Pre-HONEYCOMB 版本前可能先调用onSaveInstanceState,之后onPause先调用)。Android Activity的详细文档在这里。

再来看函数名,onSaveInstanceState,保存的是Activity实例的状态,强调Instance。onPause是生命周期的一部分,属于正常的生老病死,没什么好解释的,如果想加强记忆,可以看gasolin 的这篇https://code.google.com/p/androidbmi/wiki/LifeCycle。

默认的Activity onSaveInstanceState方法会做保存带id的view(Edittext这样的控件)的状态。我对view不甚了解,原文是:

“The default implementation takes care of most of the UI per-instance state for you by callingonSaveInstanceState() on each view in the hierarchy that has an id, and by saving the id of the currently focused view (all of which is restored by the default implementation ofonRestoreInstanceState(Bundle)). If you override this method to save additional information not captured by each individual view, you will likely want to call through to the default implementation, otherwise be prepared to save all of the state of each view yourself. ”

什么时候要重载onSaveInstanceState呢?绝大部分时候。但是因为默认的Activity onSaveInstanceState函数做了保存view状态的工作,所以重载的机会大大减少,变成如果你用了其它控件的时候(例如你自己做的画图控件,或者需要保存activity的一些属性值,如session id), 需要重载onSaveInstanceState。否则你的activity被回收后重新进入,图形数据全没了。

还有一个问题:什么时候需要重载onPause呢?释放资源的时候,这个很好理解;还有,你想在正常退出程序保存数据时。第二个重载原因有点违反直觉,要我给app例子的话我能想到“短信”、“记事本”,还有Android示例代码里的notepad。手机的操作大部分都是按返回键或者Home键,你分不清用户是要关闭你的程序还是切到其它app里,所以不管三七二十一,数据统统在onPause里存下来。当然,如果你要做得够细,需要在onDestroy里询问用户要不要保存,但有时onDestroy根本得不到机会执行activity就被kill掉了。如果再考虑调用其它activity时原来activity的onDestroy会被调用,就更拎不清。

onSaveInstanceState存储内容的方式和onPause不一样。onSaveInstanceState是存在系统缓存里,onPause写persistent data。为什么要这样呢? 因为Instance data只是在重新create activity时用,换句话说只是对app编写者有用,而onPause存下来的是对app用户有用的数据。

最后,让我们来想想Android的重启提示。如果你的app被后台kill掉了,onSaveInstanceState非常及时的把数据存在了Bundle里,但是用户选择了关机,Bundle里的数据还在吗?



0 0
原创粉丝点击