您的位置:首页 > 移动开发 > Android开发

android学习笔记——onSaveInstanceState的使用

2016-05-03 14:53 459 查看
//保存当前所有的棋子的位置,在返回应用的时候,重新显示
@Override
protected Parcelable onSaveInstanceState()
{
Bundle bundle=new Bundle();
bundle.putParcelable(INSTANCE, super.onSaveInstanceState());
bundle.putBoolean(INSTANCE_GAME_OVER, isGameOver);
bundle.putParcelableArrayList(INSTANCE_WHITE_ARRAY, mWhiteArray);
bundle.putParcelableArrayList(INSTANCE_BLACK_ARRAY, mBlackArray);

return bundle;
}
//当该activity没有销毁,重新获得焦点的时候载入保存的数据!
@Override
protected void onRestoreInstanceState(Parcelable state)
{
if(state instanceof Bundle){  //判断state是否为bundle类型
Bundle bundle=(Bundle) state;
isGameOver=bundle.getBoolean(INSTANCE_GAME_OVER);
mWhiteArray=bundle.getParcelableArrayList(INSTANCE_WHITE_ARRAY);
mBlackArray=bundle.getParcelableArrayList(INSTANCE_BLACK_ARRAY);
super.onRestoreInstanceState(bundle.getParcelable(INSTANCE));
return ;
}
// TODO Auto-generated method stub
super.onRestoreInstanceState(state);
}


要保存当前的程序运行的数据时,要使用一个Bundle 来保存数据;其是一个使用类似键值对的形式保存;

. onSaveInstanceState和onRestoreInstanceState基本作用

onSaveInstanceState是用来保存UI状态的,你可以使用它保存你所想保存的东西,在Activity杀死之前,它一般在onStop或者onPause之前触发,onRestoreInstanceState则是在onResume之前触发回复状态,至于复写这个方法后onCreate方法是否会被调用。

关于onSaveInstanceState (),是在函数里面保存一些View有用的数据到一个Parcelable对象并返回。在Activity的onSaveInstanceState(Bundle outState)中调用View的onSaveInstanceState (),返回Parcelable对象,
  接着用Bundle的putParcelable方法保存在Bundle savedInstanceState中。

  当系统调用Activity的的onRestoreInstanceState(Bundle savedInstanceState)时, 同过Bundle的getParcelable方法得到Parcelable对象,然后把该Parcelable对象传给View的onRestoreInstanceState (Parcelable state)。在的View的onRestoreInstanceState中从Parcelable读取保存的数据以便View使用。
  这就是onSaveInstanceState() 和 onRestoreInstanceState() 两个函数的基本作用和用法
二 其onSaveInstanceState方法会在什么时候被执行,有这么几种情况:

1、当用户按下HOME键时

这是显而易见的,系统不知道你按下HOME后要运行多少其他的程序,自然也不知道activity A是否会被销毁,故系统会调用onSaveInstanceState,让用户有机会保存某些非永久性的数据。以下几种情况的分析都遵循该原则

2、长按HOME键,选择运行其他的程序时。

3、按下电源按键(关闭屏幕显示)时。

4、从activity A中启动一个新的activity时。

5、屏幕方向切换时,例如从竖屏切换到横屏时

三. onSaveInstanceState()方法的默认实现

  如果我们没有覆写onSaveInstanceState()方法, 此方法的默认实现会自动保存activity中的某些状态数据, 比如activity中各种UI控件的状态.。android应用框架中定义的几乎所有UI控件都恰当的实现了onSaveInstanceState()方法,因此当activity被摧毁和重建时, 这些UI控件会自动保存和恢复状态数据. 比如EditText控件会自动保存和恢复输入的数据,而CheckBox控件会自动保存和恢复选中状态.开发者只需要为这些控件指定一个唯一的ID(通过设置android:id属性即可), 剩余的事情就可以自动完成了.如果没有为控件指定ID, 则这个控件就不会进行自动的数据保存和恢复操作。

  由上所述, 如果我们需要覆写onSaveInstanceState()方法, 一般会在第一行代码中调用该方法的默认实现:super.onSaveInstanceState(outState)。
四. 是否需要重写onSaveInstanceState()方法

既然该方法的默认实现可以自动的保存UI控件的状态数据, 那什么时候需要覆写该方法呢?

  如果需要保存额外的数据时, 就需要覆写onSaveInstanceState()方法。大家需要注意的是:onSaveInstanceState()方法只适合保存瞬态数据, 比如UI控件的状态, 成员变量的值等,而不应该用来保存持久化数据,持久化数据应该当用户离开当前的activity时,在onPause()中保存(比如将数据保存到数据库或文件中)。说到这里,还要说一点的就是在onPause()中不适合用来保存比较费时的数据,所以这点要理解。

  由于onSaveInstanceState()方法方法不一定会被调用, 因此不适合在该方法中保存持久化数据, 例如向数据库中插入记录等. 保存持久化数据的操作应该放在onPause()中。若是永久性值,则在onPause()中保存;若大量,则另开线程吧,别阻塞UI线程。
本文 借鉴 leesa的博客 的说明
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: