Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

android - When exactly are onSaveInstanceState() and onRestoreInstanceState() called?

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

enter image description here

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):

enter image description here

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...