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

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...