Killed Android service and static variables

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

This service supports some states using the static fields of class classes. I expect static fields to retain their values, even though the service was killed and the OS restarted.

But it doesn't seem to be that way. After a reboot, the static reset variables are equal to the default value. Is this what is supposed to happen? Should I use a different way to maintain a constant state despite kill / restart?

+6
source share
1 answer

Yes, this is what happens when your service is killed. The program is removed from memory, and when it is reloaded into memory, all default values ​​for static variables are accepted. In other words, the bytecode for your program cannot change from execution to execution.

As a rule, it was considered that it is bad to use static variables to maintain state. Try storing them in a repository stored in the repository, like a sqlite database.

+6
source

Source: https://habr.com/ru/post/901745/


All Articles