Android Application saving data when app in background

3.4k views Asked by At

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

2

There are 2 answers

6
Basile Perrenoud On BEST ANSWER

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

0
keshav On