Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

android - onSaveInstanceState() and onPause()

I'm a little bit confused about these two methods in Android.

From the documentation I understand that onSaveInstanceState() should be called to store only temporary information, and onPause() should be used to store any persistent data.

I was wondering why to call onSaveInstance() at all, when onPause() is called every time. Then I read in the Notepad tutorial:

"Note that saveState() must be called in both onSaveInstanceState() and onPause() to ensure that the data is saved. This is because there is no guarantee that onSaveInstanceState() will be called and because when it is called, it is called before onPause()."

There is no guarantee that onSaveInstanceState() will be called because you can simply walk out of the activity using the back button.

But according to this if you don't save the persistent data inside both methods, the app might be killed while inside onSaveInstanceState().

So we need to save the persistent data in both methods actually, am I right?

But if this is true, isn't this too much of an overhead and maybe there should be some other additional flag to tell if the method is already called or something?

http://developer.android.com/resources/tutorials/notepad/notepad-ex3.html

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

From the developer guide on activities:

Note: Because onSaveInstanceState() is not guaranteed to be called, you should use it only to record the transient state of the activity (the state of the UI)—you should never use it to store persistent data. Instead, you should use onPause() to store persistent data (such as data that should be saved to a database) when the user leaves the activity.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...