在前天,为了测试一个功能,单独拎出来写了一个小demo。但是跑的时候,却始终白屏。就好像ContentView始终没有set进去一样。

困了快一个小时才突然发现是为什么。

原来,onCreate方法不止一个。
正常我们使用的方法是onCreate(Bundle savedInstace),这是我们正常使用的方法,但是我在通过IDE覆盖的时候,却不小心覆盖成了onCreate(Bundle savedInstance, PersistableBundle)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Same as {@link #onCreate(android.os.Bundle)} but called for those activities created with
* the attribute {@link android.R.attr#persistableMode} set to
* <code>persistAcrossReboots</code>.
*
* @param savedInstanceState if the activity is being re-initialized after
* previously being shut down then this Bundle contains the data it most
* recently supplied in {@link #onSaveInstanceState}.
* <b><i>Note: Otherwise it is null.</i></b>
* @param persistentState if the activity is being re-initialized after
* previously being shut down or powered off then this Bundle contains the data it most
* recently supplied to outPersistentState in {@link #onSaveInstanceState}.
* <b><i>Note: Otherwise it is null.</i></b>
*
* @see #onCreate(android.os.Bundle)
* @see #onStart
* @see #onSaveInstanceState
* @see #onRestoreInstanceState
* @see #onPostCreate
*/
public void onCreate(@Nullable Bundle savedInstanceState,
@Nullable PersistableBundle persistentState) {
onCreate(savedInstanceState);
}

我们知道,第一个Bundle是意外终止时,才会被调用的。比如转化屏幕的方向(横竖方向),Activity就会被终止,这时候,系统就会调用onSaveInstance方法,让你把信息记录下来,在下一次onCreate重建界面的时候,就可以利用savedInstance来重新构建对象。(当然,在onRestore中重新构建对象也是可以的)

而PersistableBundle看上面注释上说,应该与电池以及开关机有关。如果我猜的不错,应该是当电量不足关机的时候,会保存这个Activity的状态到PersistableBundle,从而重新初始化。


刚交了一期任务,还算轻松,准备把最近的多总结一下。另外,可能考虑,要开心坑了。