android – 什么时候调用onSaveInstanceState()和onRestoreInstanceState()?

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

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

我知道当一个活动即将被销毁时,onSaveInstanceState()是not always called.例如,如果由于用户按下“后退”按钮而导致销毁,则不会保留活动状态.但是在保存和恢复状态的情况下,调用onSaveInstanceState()/ onRestoreInstanceState()时,它们究竟被调用了吗?

例如,根据上面的图,onRestoreInstanceState()可能在onStart()之前,或在onStart()之后但在onResume()之前或onResume()之后被调用.类似地,onSaveInstanceState()存在几种可能性.那他们什么时候打电话呢?

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

解决方法:

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

上一篇:SQLserver还原提示正在还原中。解决方法


下一篇:Leetcode: 1416. Restore The Array