onSaveInstanceState() 和 onPause() 调用顺序
关于 onSaveInstanceState()
的文档指出:
如果调用该方法,它总是在 onStop() 之前调用,也可能在 onPause() 之前调用。
但是,我从日志消息中始终注意到 onPause()
始终在 onSaveInstanceState()
之前调用。我已将日志消息放入这两个方法中。请帮我理解在什么情况下onSaveInstanceState()
会在onPause()
之前调用。
环境:Android v4.0 (API 14) + Eclipse v3.7.1 - Indigo。
The documentation on onSaveInstanceState()
states:
If the method is called, it is always called before onStop() and possibly before onPause().
But, I notice, consistently, from log messages that onPause()
is ALWAYS CALLED BEFORE onSaveInstanceState()
. I had put log messages in these two methods. Please help me understand in what circumstances does onSaveInstanceState()
is called before onPause()
.
Environment: Android v4.0 (API 14) + Eclipse v3.7.1 - Indigo.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以此处了解相关内容。
简而言之,您永远无法知道 onSaveInstanceState 何时运行。
You can read about that here.
In a nutshell you can't never know about time when onSaveInstanceState will be run.
HONEYCOMB 之前的平台和其他平台(自 HONEYCOMB 开始)之间的 Activity 生命周期存在差异:
API 级别 >= 11:当
onPause()
被调用,进程处于安全状态,无法被杀死。API级别< 11 :当调用
onPause()
时,承载 Activity 的进程将变为可终止状态。这意味着系统可以终止包含该活动的进程,而不执行任何其他代码行。因此,如果发生这种情况,onSaveInstanceState()
可能永远不会被调用。为了避免这种情况,系统应该在onPause()
之前调用onSaveInstanceState()
,否则将无法保存用户状态。There is a difference in the Activity lifecycle between the pre-HONEYCOMB and the other platforms (since HONEYCOMB onwards):
API level >= 11: when
onPause()
is called, the process is in a safe state, it can't be killed.API level < 11 : when
onPause()
is called, the process that hosts the Activity becomes killable. It means that the system can kill the process, that contains the activity, without executing any other line of code. So if this happens theonSaveInstanceState()
may never be called. In order to avoid this, the system should callonSaveInstanceState()
beforeonPause()
, otherwise you will not able to save the user state.onSaveInstanceState() 很好,但唯一有保证的回调是 onPause(),当您的 Activity 失去焦点时调用。所以,保存你的状态
onSaveInstanceState() is nice, but only guaranted callback is onPause(), called when your activity loses focus. So, save your state there