onSaveInstanceState的用法

1 The system calls this method before making the activity vulnerable to being destroyed and passes it a Bundle object. The Bundle is where you can store state information about the activity as name-value pairs, using methods such as putString(). Then, if the system kills your activity's process and the user navigates back to your activity, the system passes the Bundle to onCreate() so you can restore the activity state you saved during onSaveInstanceState(). If there is no state information to restore, then the Bundle passed to onCreate()is null.

  一般onSaveInstanceState(Bundle ) 和 onCreate(Bundle ) 结合使用来保存activity的状态,但是文档里面指出了几个问题:系 统不会保证onSaveInstanceState()在activity被销毁前总被调用(因为有一些不需要保存状态的情况,比如,用户用BACK键关 闭此activity);如果onSaveInstanceState()被调用,那么一定是在onStop()之前,或者可能在onPause()之 前。

 

2 如果你在onSaveInstanceState()不做啥事(不重载它),有些activity的状态也会被activity默认的 onSaveInstanceState()保存。比如,通常EditText会保存自己的状态,原因就是activity默认的 onSaveInstanceState()会调用其layout里面每一个View的onSaveInstanceState(),当然也包括此 EditView。你只需要为这些view提供唯一的ID(android:id属性),他们就会保存自己的状态,不用你操心了。这个自动保存可以通过 android:saveEnabled属性或者 setSaveEnabled()方法 来禁用。

 

3 “onSaveInstanceState() 只应该被用来保存activity暂时的状态(例如,类成员变量的值关联着UI),而不应该用来保存持久化数据。持久化数据应该当用户离开当前的 activity时,在 onPause() 中保存(比如,保存到数据库)。”  这里用onPause()令我不理解,因为文档前面提过,onPause()时,activity并没有完全看不到,而只是可能有个dialog盖住 它,所以不建议在onPause()中做耗时的工作。(这里我只能将写入数据库理解为轻量级操作了。。。。暂时我觉得持久化数据应该在 onDestroy()中做)。

 

4 可以用旋转屏幕来测试你的程序保存状态的能力。因为一般旋转时,activity会被重新 onCreate() onStart()等等,程序此时能够保存状态是很重要的。

posted @ 2012-05-02 17:06  DuSizhong  阅读(1298)  评论(0编辑  收藏  举报