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

java - How do I make Android's Singleton object persistent

In my app, I have a singleton class which communicates with all the activities and has all the app data. All of a sudden the object has started becoming null. It seems to be happening when i change top level activity (using intent). Is there a simple method the make sure that as long as my activity is visible the object persists.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I think a new top-level activity is made in a new process (reading between the lines in http://developer.android.com/reference/android/app/Activity.html#ProcessLifecycle).

Android is more likely to kill of the process of an Activity that lives in the background, and that includes when a top-level activity drops behind another.

I think a better solution might be to have your Singleton transparently initialise itself if null, loading and saving any state from disk if necessary (a pretty standard singleton paradigm). There's no way to solve your problem with a single instance across the old and new activities.

Edit: I'm not convinced that a Service is the way to go. Services are for carrying on with activities in the background of the phone, whereas what you're talking about is data storage and retrieval. The most natural way to do that, I think, is for each Activity to be robust to whether it's the first activity or not.


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

...