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
515 views
in Technique[技术] by (71.8m points)

android - Saving Activity State in the onPause

I have a variable that I have successfully saved and restored using onSaveInstanceState

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState); // the UI component values are saved here.
    outState.putDouble("VALUE", liter);
    Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG).show();
}

But this only works if the activity is destroyed. I want to save the same variable by overriding the onPause() method and getting back when the activity is not not paused anymore any ideas on how to do this are greatly appreciated

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

As you have discovered, onSaveInstanceState is useful only in situations where you need to recreate the same so-called "instance" of the Activity after it has been destroyed by the OS, usually because it is too far in the back stack to stay alive under memory pressure.

Saving your data in onPause is indeed the way to go for persistence that lasts beyond a single execution of your Activity. To get this working, you have several options, including:

  • Shared Preferences
  • Files
  • Databases
  • Content Providers

I suggest reading this documentation to learn more about each of these options:

http://developer.android.com/guide/topics/data/data-storage.html


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

1.4m articles

1.4m replys

5 comments

57.0k users

...