Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Killed Android service and static variables

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?

like image 908
gpo Avatar asked Nov 17 '11 19:11

gpo


People also ask

How do you destroy static variables?

You cannot destroyed static variable. Everyone can access static variable without declaring class instance. Its a shared memory concept.

What is static variable in Android?

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.


1 Answers

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.

like image 185
Kurtis Nusbaum Avatar answered Oct 07 '22 02:10

Kurtis Nusbaum