Android Application saving data when app in background

☆樱花仙子☆ 提交于 2019-12-07 20:43:19

问题


currently I'm developing xmmp client which is working quite fine when app is in foreground. But due to the fact that im keeping quite lot of data in Application class (complex ArrayList, Strings and booleans as public statics) when app is in background every field is being garbage-collected.

So my question is what is the best way to retrieve this data when i get app from background? Its quite a problem because I use this public statics in every class so far and it causes my app to crash. The problem is the fact that user can put app in background from every activity and repopulating data in Application class seems like something hard. Maybe there is another way of keeping data with global access to them, that wont be wiped down in background?

Thanks in advance


回答1:


If the problem is that your app is destroyed by android when in backgroud, the standard way to do would be to save data in the onDestroy() function of your main activity, and retrieve this data in the onCreate method when to app is opened again ( using the bundle).

If you want the data to persist even when the phone is turned off, you can considere permanent storage options like a database. Have a look at http://developer.android.com/guide/topics/data/data-storage.html

Finally, if you would like a way to keep running in background, you could have a look at the Service class. But if would demand some more coding from you to be able to communicate between your service and the activity




回答2:


Try to use sharedpreferences see following example

http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/



来源:https://stackoverflow.com/questions/20539042/android-application-saving-data-when-app-in-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!