[Android] About Activity’s onSaveInstanceState life cycle

Recently, when I was interviewing for a job at a major company, I was asked about the life cycle of the Activity. The interviewer emphatically asked onSaveInstanceStatewhether the call was before or after onStop. I was a little confused at the time and had not paid attention to whether it was before or after onStop. .

But does it matter when this method is called? We just use it to save data and then onRestoreInstanceStaterestore it.

Regardless of whether it's important or not, since the interviewer asked about it and you don't know it, go and verify it.

Later, the author personally wrote the code to verify it, and found that it was called after onStop. At the same time, I also read other people's answers online and found that many materials were written after onPause and before onStop. Isn’t it reliable that I personally verified it?

Then the author went to Google's official website to check its official description. After reading it, I was shocked. It turns out that there is a lot to learn about this onSaveInstanceStatemethod!

Take a screenshot first:

Insert image description here

It can be seen from the official description that this method is used to save data when the Activity is killed by the system. We can restore the data when the Activity is restored or onCreateduring onRestoreInstanceStatethe life cycle.

The key point is that the last paragraph of the description points out that if onSaveInstanceStateit is called, if the target platform of the application is Android P (9), onSaveInstanceStateit will be called after onStop. If the target platform is before Android 9, onSaveInstanceStateit will be called before onStop, and it is not guaranteed to be onPause. Called before or after.

Now I finally know why my verification was after onStop, but my online profile said it was before onStop.

So onRestoreInstanceStateare there similar differences?

Insert image description here
Depending on the situation, this method is called between and , there is no version difference onStart.onPostCreate

Guess you like

Origin blog.csdn.net/devnn/article/details/133081696
Recommended