http://www.jianshu.com/p/89e0a7533dbe
写的很好~~ 作为参考
- 起因
发现在手机里菜单键, 然后点击叉叉, 杀了进程后, 再打开, 发现:
ScrollView 会自动滚回刚才离开时的位置
TextView 会自动设置成刚才离开时的text
后来看ScrollView的实现, 发现在每次杀进程后再打开进程, 会执行onRestoreInstanceState并传入参数, 参数中有一项 ScrollPosition记录的是刚才滚动的位置. 当此ScrollView在重新打开后第一次layout的时候, 会取到这个scrollPosition, 并scrollto相应的位置
TextView实现也是类似, 重写了onSaveInstanceState 记录状态, 并onRestoreInstanceState恢复状态.
onSaveInstanceState在应用有可能在用户非有意情况下销毁的时候执行. onPause 和onStop 执行, 顺序不一定
onRestoreInstanceState 在应用确实销毁了后, 再重新打开时执行, onCreate之后, onStart之后.顺便看了Parcelable(store数据的基本格式), 大概是本来一个java的对象, 变成Parcelable的格式可以进行存储和传输. 等下次你拿到还可以恢复.
重要:
When your activity is recreated after it was previously destroyed, you can recover your saved state from the Bundle that the system passes your activity. Both the onCreate() and onRestoreInstanceState() callback methods receive the same Bundle that contains the instance state information.
Because the onCreate() method is called whether the system is creating a new instance of your activity or recreating a previous one, you must check whether the state Bundle is null before you attempt to read it. If it is null, then the system is creating a new instance of the activity, instead of restoring a previous one that was destroyed.
onCreate() 和 onRestoreInstanceState()用的是同样的恢复数据........
- Activity 和 view的 onSaveInstanceState and onRestoreInstanceState
在Activity的保存的状态里有一项: Key=android:viewHierarchyState, content=null 保存的是view的状态. Activity 的save和restore的时候, 要通过mWindow调用 mContentParent的所有子view的save和restore.
自己打印的格式, 大概可以看:
Key=android:viewHierarchyState, content = bundle: {
Key=android:views, content = array1: { null
Key=android:views, content = array2: { {16908290=android.view.AbsSavedState$1@b1b4601, 2131623936=FragmentPager.SavedState{fb74ca6 position=0}, 2131623937=android.view.AbsSavedState$1@b1b4601, 2131623938=android.view.AbsSavedState$1@b1b4601, 2131623939=android.view.AbsSavedState$1@b1b4601, 2131623940=android.view.AbsSavedState$1@b1b4601, 2131623990=android.view.AbsSavedState$1@b1b4601, 2131623991=android.view.AbsSavedState$1@b1b4601, 2131623992=android.view.AbsSavedState$1@b1b4601, 2131623993=android.view.AbsSavedState$1@b1b4601, 2131624000=miui.widget.ScreenView$SavedState@8ca66e7, 2131624001=android.view.AbsSavedState$1@b1b4601, 2131624002=android.view.AbsSavedState$1@b1b4601, 2131624003=TextView.SavedState{7326294 start=6 end=6 text=七十二层奇楼}, 2131624004=android.view.AbsSavedState$1@b1b4601, 2131624005=android.view.AbsSavedState$1@b1b4601, 2131624006=HorizontalScrollView.SavedState{cf5413d scrollPosition=0}, 2131624020=android.view.AbsSavedState$1@b1b4601, 2131624026=android.view.AbsSavedState$1@b1b4601, 2131624030=android.view.AbsSavedState$1@b1b4601, 2131624031=android.view.AbsSavedState$1@b1b4601, 2131624032=android.view.AbsSavedState$1@b1b4601, 2131624033=android.view.AbsSavedState$1@b1b4601, 2131624034=android.view.AbsSavedState$1@b1b4601}