onSaveInstanceState onRestoreInstanceState 在生命周期里的顺序
程序员文章站
2022-04-22 23:21:44
12-09 22:57:13.727 D/Lifecycle: onCreate12-09 22:57:13.879 D/Lifecycle: onStart12-09 22:57:13.889 D/Lifecycle: onResume--------------- 旋转画面 -----------------------12-09 22:57:19.375 D/Lifecycle: onPause12-09 22:57:19.375 D/Lifecycle: onSaveInstanceSt....
12-09 22:57:13.727 D/Lifecycle: onCreate 12-09 22:57:13.879 D/Lifecycle: onStart 12-09 22:57:13.889 D/Lifecycle: onResume --------------- 旋转画面 ----------------------- 12-09 22:57:19.375 D/Lifecycle: onPause 12-09 22:57:19.375 D/Lifecycle: onSaveInstanceState (有些文章说 onSaveInstanceState在onPause之后) 12-09 22:57:19.379 D/Lifecycle: onStop 12-09 22:57:19.379 D/Lifecycle: onDestroy 12-09 22:57:19.434 D/Lifecycle: onCreate 12-09 22:57:19.434 D/Lifecycle: onActivityResult 12-09 22:57:19.434 D/Lifecycle: onReStart 12-09 22:57:19.507 D/Lifecycle: onStart 12-09 22:57:19.508 D/Lifecycle: onRestoreInstanceState 12-09 22:57:19.510 D/Lifecycle: onResume
如果画面有dialog,fragment,在onRestoreInstanceState之前show的话,由于还没有状态,show里面执行commit时会发生以下提示错误。
Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState (编者:onSaveInstanceState之前实现commit的话,commit之后的状态就不被保存了。commit之后再onSaveInstanceState才能把frag状态保存下来)
//onResum之前show的逻辑,移到onResume里
/** 把显示逻辑保存下来 */
private var showFragmentsTask: (() -> Unit)? = null
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
//when (requestCode) {
// //show frag1处理
// //show frag2处理
//}
把上面的处理放到变量里
showFragmentsTask = when (requestCode) {
//show frag1处理
//show frag2处理
else -> null
}
}
override fun onResumeFragments() {
super.onResumeFragments()
showFragmentsTask ?.invoke()
showFragmentsTask = null
}
参考
commitallowingstateloss 和commit的区别 https://www.dazhuanlan.com/2020/02/09/5e4006bd7e8ae/
onActivityResult 调用时机 https://kokufu.blogspot.com/2012/09/onactivityresult.html
错误回避方法 https://kokufu.blogspot.com/2014/08/onactivityresult-dialogfragmentshow.html
本文地址:https://blog.csdn.net/vovo2000/article/details/107930230
上一篇: Android推送之华为推送