重建Actity

保存Activity状态

09-15 11:09:56.002 5292-5292/com.example.li.restartactivity D/test: onsaveInstanceStateweds
09-15 11:09:56.002 5292-5292/com.example.li.restartactivity D/test: stop

当我们的activity开始Stop之前,系统会调用 onSaveInstanceState()

Activity可以用键值对的集合来保存状态信息。这个方法会默认保存Activity视图的状态信息,如在 EditText 组件中的文本或 ListView 的滑动位置。

为了给Activity保存额外的状态信息,你必须实现onSaveInstanceState() 并增加key-value pairs到 Bundle 对象中,例如:

static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
...

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current game state
    savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
    savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);

    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}

Caution: 必须要调用 onSaveInstanceState() 方法的父类实现,这样默认的父类实现才能保存视图状态的信息。


---------------------------------------》

两种恢复ancticvity的方法

1,

由于 onCreate() 方法会在第一次创建新的Activity实例与重新创建之前被Destory的实例时都被调用,我们必须在尝试读取 Bundle 对象前检测它是否为null。如果它为null,系统则是创建一个新的Activity实例,而不是恢复之前被Destory的Activity。

下面是一个示例:演示在onCreate方法里面恢复一些数据:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); // Always call the superclass first

    // Check whether we're recreating a previously destroyed instance
    if (savedInstanceState != null) {
        // Restore value of members from saved state
        mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
        mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
    } else {
        // Probably initialize members with default values for a new instance
    }
    ...
}
2,onRestoreInstanceState()方法会在 onStart() 方法之后执行. 系统仅仅会在存在需要恢复的状态信息时才会调用 onRestoreInstanceState() ,因此不需要检查 Bundle 是否为null。
public void onRestoreInstanceState(Bundle savedInstanceState) {
    // Always call the superclass so it can restore the view hierarchy
    super.onRestoreInstanceState(savedInstanceState);

    // Restore state members from saved instance
    mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
    mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
}

Caution: 与上面保存一样,总是需要调用onRestoreInstanceState()方法的父类实现,这样默认的父类实现才能保存视图状态的信息。

/*@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {


    String text = savedInstanceState.getCharSequence(STORE).toString();
    editText.setText(text);//因为editeText跳转到其他的Activty是没有指定一个view所以会报空指正异常需要
    //重写指定一个view就可以了
    editeText=(EditeText)findViewById(R.layout.text);
    editText.setText(Text);

    super.onRestoreInstanceState(savedInstanceState);

}*/



你可能感兴趣的:(activity生命周期)