简体   繁体   中英

Saving the state of a singleton in Android?

I have a singleton data manager for a specific part of my application. This data manager holds the state of a multistep process between activities. This works perfectly except when the application is placed into the background for an extended period of time as the data manager is cleared from memory. My question is what is the best way to save the state of a singleton that isn't part of one specific activity? All activity state is saved using onSaveInstanceState callback, does Application receive a callback to save state?

您可以在每次状态更改时将状态保存在SharedPrefs中 ,并在每次初始化单例时从SharedPrefs中获取状态。

I have had some similar experiences and the easiest one, straight out of my head, would be either to use the onSaveInstanceState or, persist the whole thing locally in SQLite or perhaps in the SharedPreferences , even if that might not be the right approach for this task.

If you want I can provide you with some sample code for either of the options, otherwise please check the following:

SharedPreferences : http://www.vogella.com/articles/AndroidFileBasedPersistence/article.html

SQLite: http://www.vogella.com/articles/AndroidSQLite/article.html

Saving and recieving instance state: How to use onSavedInstanceState example please

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