在内存不足时,Activity被回收,recreate()是Activity再次恢复的过程。
recreate()的方法内容为:
/**
* Cause this Activity to be recreated with a new instance. This results
* in essentially the same flow as when the Activity is created due to
* a configuration change -- the current instance will go through its
* lifecycle to {@link #onDestroy} and a new instance then created after it.
*/
public void recreate() {
if (mParent != null) {
throw new IllegalStateException("Can only be called on top-level activity");
}
if (Looper.myLooper() != mMainThread.getLooper()) {
throw new IllegalStateException("Must be called from main thread");
}
mMainThread.requestRelaunchActivity(mToken, null, null, 0, false, null, false);
}
可以看到这个方法有两个IllegalStateException处理。一是,当前需要重建的Activity就处在顶层结构,没有父容器包裹它;二是,必须在主线程里调用。requestRelaunchActivity方法将重新启动Activity。
在ONCE项目中是为了无需重启更新主题所做的处理,即在SettingActivity更换主题之后,通知MainActivity调用recreate方法重新构建MainActivity。
另外可以下面两个方法进行数据的保存和恢复:
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt("DATA", 1);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
int data = savedInstanceState.getInt("DATA");
}