我想在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:
答案 0 :(得分:1)
答案 1 :(得分:1)
正如the official reference所说onSaveInstanceState
:
在活动被杀之前调用此方法
如果Activity
被杀死的可能性,onSaveInstanceState
将被称为实际上会被杀死的人。
当实际 onRestoreInstanceState
已被杀死时调用Activity
。
因此,如果实际上Activity
尚未被杀死,则不会调用onRestoreInstanceState
。
因此,onSaveInstanceState
和onRestoreInstanceState
之间的不对称调用可能会发生。如果你想确保被叫onRestoreInstanceState
,你肯定会杀死你的Activity
。