简体   繁体   中英

Android application - saving state

I have my own Application class object where I store all application data. In Application.onCreate I create all applications objects and read data from SharedPreferences. My problem is that when the application goes to background it may be killed. After I select the app from launcher, the activity stack is restored (the last Activity is launched, instead of Launcher Activity). The problem is the Application.onCreate is not called thus all applications objects are not loaded and I run into troubles. WHat is the best way to store/restore Application data/object. I know that it can be done in Activities.onCreate/onDestroy but I have many Activities in my app and do not know, which on them will be on top when the application is killed/restarted.

Serialize your ApplicationObject and store it to a File (simple) or Object Store (complex)

or you can implement a Serialize / Deserialize functionality

Where , Serialize will convert object properties to JSON and store

DeSerialize will loads the JSON and populate the Object and returns.

When you launch your application and it starts from the last activity and not from the launcher activity, it means that your application has not been killed. So in this case, your application's onCreate method will not be called, because it is still alive.

Application's onCreate method is called once during the lifecycle of the app. So until your app class is alive, you should have all your application data accessible.

If you need to test, what happens when your application has been killed, so you should go to the "application manager" and kill manually the app.

EDIT: if your application is alive, as long as your application has a reference to the data, they can not be removed by gc. So, in your case, perhaps you forgot to update the data correctly. So serializing will not help you in this case, otherwise you will have bugs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM