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?
You cannot destroyed static variable. Everyone can access static variable without declaring class instance. Its a shared memory concept.
Static variables are also known as Class variables which are declared with the “static” keyword in a class. A single copy of each variable per class is to be shared by all instances of the class. Static variables are stored in static memory.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With