onSaveInstanceState() 和 onRestoreInstanceState() 什么时候被调用? [英] When exactly are onSaveInstanceState() and onRestoreInstanceState() called?

查看:24
本文介绍了onSaveInstanceState() 和 onRestoreInstanceState() 什么时候被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下图(来自):

我知道 onSaveInstanceState()不总是在活动即将被销毁时调用.例如,如果它因为用户按下了返回"按钮而被销毁,则不会保留活动状态.但是在状态保存和恢复,并且onSaveInstanceState()/onRestoreInstanceState()被调用的情况下,究竟是什么时候他们打电话给?

例如,根据上图,onRestoreInstanceState()可能在onStart()之前被调用,也可能在onStart()之后被调用,但是onResume() 之前,或 onResume() 之后.类似地,onSaveInstanceState() 存在几种可能性.那么它们究竟在什么时候被调用?

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

解决方案

根据 文档:

<块引用>

void onRestoreInstanceState (Bundle savedInstanceState)

这个方法在onStart()onPostCreate(Bundle)之间调用.

void onSaveInstanceState (Bundle outState)

如果调用,此方法将在 onStop() 之后针对以 Build.VERSION_CODES.P 开头的平台为目标的应用程序发生.对于面向早期平台版本的应用程序,此方法将在 onStop() 之前发生,并且无法保证它是在 onPause() 之前还是之后发生.

The following figure (from the official doc) describes the well-known lifecycle of an Android activity:

On the other hand, when the activity is destroyed by the system (for example because memory needs to be reclaimed), the state of the activity is sometimes automatically saved and restored by means of the methods onSaveInstanceState() and onRestoreInstanceState(), as illustrated by the following figure (also from the official doc):

I'm aware that onSaveInstanceState() is not always called when an activity is about to be destroyed. For example, if it is destroyed because the user has pressed the "back" button, the activity state is not preserved. But in the cases when the state is saved and restored, and onSaveInstanceState() / onRestoreInstanceState() get called, when exactly are they called?

For example, according to the above figures, onRestoreInstanceState() might be called before onStart(), or after onStart() but before onResume(), or after onResume(). Similarly, several possibilities exist for onSaveInstanceState(). So when are they called exactly?

Ideally, what I would like is to see a combined diagram showing the activity lifecycle states and the save/restore methods, if that exists.

解决方案

Per the 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().

这篇关于onSaveInstanceState() 和 onRestoreInstanceState() 什么时候被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆