android - 究竟何时调用 onSaveInstanceState() 和 onRestoreInstanceState()?

标签 android android-activity restore android-lifecycle

下图(来自 the official doc)描述了众所周知的 Android Activity 的生命周期:

enter image description here

另一方面,当activity被系统销毁时(例如因为内存需要回收),activity的状态有时会通过方法自动保存和恢复 onSaveInstanceState()onRestoreInstanceState(),如下图所示(同样来自the official doc):

enter image description here

我知道 onSaveInstanceState()not always called当一个 Activity 即将被销毁时。例如,如果它因为用户按下了“返回”按钮而被销毁,则不会保留 Activity 状态。但是在状态 保存和恢复,并且 onSaveInstanceState()/onRestoreInstanceState() 被调用的情况下,究竟是什么时候他们调用

例如,根据上图,onRestoreInstanceState()可能在onStart()之前调用,或者在onStart()之后调用,但是在 onResume() 之前,或在 onResume() 之后。同样,onSaveInstanceState() 也存在几种可能性。那么它们究竟是什么时候调用的呢?

理想情况下,我希望看到一个显示 Activity 生命周期状态和保存/恢复方法的组合图(如果存在)。

最佳答案

根据 documentation :

void onRestoreInstanceState (Bundle savedInstanceState)

This method is called between onStart() and onPostCreate(Bundle).

void onSaveInstanceState (Bundle outState)

If called, this method will occur after onStop() for applications targeting platforms starting with Build.VERSION_CODES.P. For applications targeting earlier platform versions this method will occur before onStop() and there are no guarantees about whether it will occur before or after onPause().

关于android - 究竟何时调用 onSaveInstanceState() 和 onRestoreInstanceState()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20831826/

相关文章:

sql-server - Pyodbc - SQL Server 数据库还原不完整

Android 在应用程序被杀死后强制完全重启

Android,线宽,像素大小

android - 如何动态交换 fragment ?

java - 端点方法不起作用,为什么?

android - 无法在 android 中获取广告 ID

android - 与父Activity通信,刷新父Activity

android - 如何开始没有 parent 的新 Activity ?

从命令行备份和恢复 MySQL

android - 如果重新创建 Activity ,是否会调用 onNewIntent 或 onActivityResult?