7

Using Android 2.1+. I have a service that gets killed from time to time by the OS (due to memory pressure I guess).

This service maintains some states using static member fields of classes. I'm expecting the static fields to keep their values despite the service being killed and restarted by the OS.

But it seems that it doesn't happen like this. After a restart, static variables are reset to default value. Is it what is supposed to happen? Should I use another way to keep a persistent state despite kill/restart?

gpo
  • 3,388
  • 3
  • 31
  • 53

1 Answers1

8

Yes, this is what happens when your service is killed. The program is taken out of memory, and when it's reloaded into memory, the default values for the static variables are all assumed. Put another way, the byte code for your program can't change from execution to execution.

It's generally considered bad from to use static variables to keep state. Try storing them in presistent storage, like a sqlite database.

Kurtis Nusbaum
  • 30,445
  • 13
  • 78
  • 102
  • 1
    I'd also specify that since static fields are reset this means OS kills the entire app Java process. And yes this happens from time to time, check this post - http://stackoverflow.com/questions/708012/android-how-to-declare-global-variables/4642069#4642069 – Vit Khudenko Nov 17 '11 at 20:38
  • 1
    Does Android really provide no means for keeping persistant state than writing it to flash every time? (for instance, onDestroy isn't guaranteed to be called!!!?) My Service changes state a LOT and this would increase battery usage and hasten flash wearout if I have to touch flash every time state changes! – Michael Mar 31 '13 at 21:15
  • @Michael From the [documentation for the onDestroy method](https://developer.android.com/reference/android/app/Activity.html#onDestroy()): Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here. – Kurtis Nusbaum Apr 02 '13 at 15:12
  • @KurtisNusbaum The [documentation for onDestroy in a Service](https://developer.android.com/reference/android/app/Service.html#onDestroy()) does not note such a restriction (although apparently it is still there), nor does Service have onPause or onSaveInstanceState. – Michael Apr 03 '13 at 18:39
  • Ooops, my bad. It's been awhile since I looked at this post and I just assumed we were talking about activities. – Kurtis Nusbaum Apr 04 '13 at 23:47