onRestoreInstanceState没有被调用

时间:2015-08-23 16:45:54

标签: android bundle android-lifecycle

我想在App进入onPause时保存textView的值。所以我实现了onSaveInstanceState和onRestoreInstanceState。但如下所示,在logcat输出中,onRestoreInstanceState 永远不会被称为。

我知道onRestoreInstanceState和onSaveInstanceState都不是App生命周期的一部分,那么为什么onSestInstanceState被调用而onRestoreInstanceState不是? 以及如何调用onRestoreInstanceState?

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    Log.w(TAG, LogAnd.i("onResume", ""));

    btAdapter = BluetoothAdapter.getDefaultAdapter();
    if (btAdapter == null) {
        tvStatus.setText("[" + SysUtils.getDeviceName() + "] no Bluetooth installed.");
    } else {
        tvStatus.setText("[" + SysUtils.getDeviceName() + "] Bluetooth installed.");
    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    // TODO Auto-generated method stub
    super.onSaveInstanceState(outState);
    Log.w(TAG, LogAnd.i("onSaveInstanceState", ""));

    outState.putString("statusText", tvStatus.getText().toString());
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onRestoreInstanceState(savedInstanceState);
    Log.w(TAG, LogAnd.i("onRestoreInstanceState", ""));

    String status = savedInstanceState.getString("statusText");
    tvStatus.setText(status);
}

logcat的

08-23 18:36:31.544: W/MainActivity(32195): -> onResume:
08-23 18:36:31.904: W/MainActivity(32195): -> onPause:
08-23 18:36:32.694: W/MainActivity(32195): -> onSaveInstanceState:
08-23 18:36:34.014: W/MainActivity(32195): -> onResume:
08-23 18:36:42.904: W/MainActivity(32195): -> onPause:
08-23 18:36:43.784: W/MainActivity(32195): -> onSaveInstanceState:
08-23 18:36:43.784: W/MainActivity(32195): -> onStop:
08-23 18:36:50.084: W/MainActivity(32195): -> onStart:BT-Receiver Registered
08-23 18:36:50.084: W/MainActivity(32195): -> onResume:

2 个答案:

答案 0 :(得分:1)

onRestoreInstanceState()仅在onStart()之后被调用,因此在onResume()之后不会调用它。检查此完整的活动生命周期。

enter image description here

我希望这有帮助!

答案 1 :(得分:1)

正如the official reference所说onSaveInstanceState

  

在活动被杀之前调用此方法

如果Activity被杀死的可能性onSaveInstanceState将被称为实际上会被杀死的人。

实际 onRestoreInstanceState已被杀死时调用Activity

因此,如果实际上Activity尚未被杀死,则不会调用onRestoreInstanceState

因此,onSaveInstanceStateonRestoreInstanceState之间的不对称调用可能会发生。如果你想确保被叫onRestoreInstanceState,你肯定会杀死你的Activity