onCreate(Bundle savedInstanceState)参数Bundle

来源:互联网 发布:mac 控制安卓手机屏幕 编辑:程序博客网 时间:2024/06/05 10:47
onCreate的方法是在Activity创建时被系统调用,是一个Activity生命周期的开始。可是有一点容易被忽视,就是onCreate方法的参数saveInsanceState。因为在一般的程序开发中,很少用到这个参数。
onCreate方法的完整定义如下:
public void onCreate(Bundle saveInsanceState){
super.onCreate(saveInsanceState);
}
 从上面的代码可以看出,onCreate方法的参数是一个Bundle类型的参数。Bundle类型的数据与Map类型的数据相似,都是以key-value的形式存储数据的。
  从字面上看saveInsanceState,是保存实例状态的。实际上,saveInsanceState也就是保存Activity的状态的。那么,saveInsanceState中的状态数据是从何处而来的呢?下面我们介绍Activity的另一个方法saveInsanceState
  onsaveInsanceState方法是用来保存Activity的状态的。当一个Activity在生命周期结束前,会调用该方法保存状态。这个方法有一个参数名称与onCreate方法参数名称相同。如下所示
public void onSaveInsanceState(Bundle saveInsanceState){
super.onSaveInsanceState(saveInsanceState);
}
 在实际应用中,当一个Activity结束前,如果需要保存状态,就在onsaveInsanceState中,将状态数据以key-value的形式放入到saveInsanceState中。这样,当一个Activity被创建时,就能从onCreate的参数saveInsanceState中获得状态数据。
 状态这个参数在实现应用中有很大的用途,比如:一个游戏在退出前,保存一下当前游戏运行的状态,当下次开启时能接着上次的继续玩下去。再比如:电子书程序,当一本小说被阅读到第199页后退出了(不管是内存不足还是用户自动关闭程序),当下次打开时,读者可能已忘记了上次已阅读到第几页了,但是,读者想接着上次的读下去。如果采用saveInstallState参数,就很容易解决上述问题。
简单的事例api中snake游戏 在SnakeView类中
复制代码
private int[] coordArrayListToArray(ArrayList<Coordinate> cvec) {
    int count = cvec.size();
      int[] rawArray = new int[count * 2];
      for (int index = 0; index < count; index++) {
          Coordinate c = cvec.get(index);
          rawArray[2 * index] = c.x;
          rawArray[2 * index + 1] = c.y;
      }
  return rawArray;
  }
  
  public Bundle saveState() {
Bundle map = new Bundle();
map.putIntArray("mAppleList", coordArrayListToArray(mAppleList));
map.putInt("mDirection", Integer.valueOf(mDirection));
map.putInt("mNextDirection", Integer.valueOf(mNextDirection));
map.putLong("mMoveDelay", Long.valueOf(mMoveDelay));
map.putLong("mScore", Long.valueOf(mScore));
map.putIntArray("mSnakeTrail", coordArrayListToArray(mSnakeTrail));
return map;
}
复制代码
在snakeActivity中实现
  
复制代码
 @Override  

publicvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.snake_layout);
mSnakeView = (SnakeView) findViewById(R.id.snake);
mSnakeView.setTextView((TextView) findViewById(R.id.text));
if (savedInstanceState == null) {
 // We were just launched -- set up a new game
mSnakeView.setMode(SnakeView.READY);
else {
// We are being restored
 Bundle map = savedInstanceState.getBundle(ICICLE_KEY);
 if (map != null) {
mSnakeView.restoreState(map);
else {
mSnakeView.setMode(SnakeView.PAUSE);
  }
  }
  }

复制代码
并重写onSavedInstanceState(),此方法会在activity结束时,调用.

  @Override  

  publicvoid onSaveInstanceState(Bundle outState) {
  //Store the game state
  outState.putBundle(ICICLE_KEY, mSnakeView.saveState());
 } 

0 0
原创粉丝点击