I’d like to know if it is safe to use static variables as a long term storage of business entities in a Mono for Android app.
For instance, if I have this class:
public class Test{
public static int MyStaticVariable{get;set;}
}
and in my main activity I have this code
protected override void OnCreate(Bundle bundle)
{
...
if (Test.MyStaticVariable){
Test.MyStaticVariable=666;
}
}
can I always rely on Test.MyStaticVariable==666 or will that value be eventually be reset by the OS when my app goes out of scope and RAM has to be recycled?
Thanks,
Adrian
The variable is scoped to your process, and will not survive a process restart (absent additional code on your part to save/restore the variable).
This is no different than Java. 🙂
If you want to save/restore the value, you should subclass Android.App.Application and override Application.OnLowMemory() and/or Application.OnTrimMemory() and save the value to persistent storage. You can then restore this value within Application.OnCreate().
(There is no way I know of to actually know when the process will be killed —
Application.OnTerminate()is only for emulators — but hopefully Android will call theOnLowMemory()/OnTrimMemory()methods before it kills the process…)