androidstatic-variablesactivity-lifecyclelow-memory

Life of public static variable in Android


Let's assume that I have an Android App with two Activities (Activity1 and Activity2). In Activity1 I declare a public static Boolean foo = true.

When I finish() Activity1 and move to Activity2, I am able to see that "foo" variable has value true

But when the System has low memory (e.g. because there are many apps running on the device) then, when I am on Activity2 I see that the value of "foo" variable is null.

How is this explained?


Solution

  • It's important to note that the life of a static variable is tied to the process not the activity. Even if your activity is destroyed, the static variable will still be alive (which is why you see it's value set to true). It's only when the process is destroyed that the static variable will be freed properly.

    This is also one of the reasons you shouldn't use static variables to hold references to activities, contexts, or views. Huge memory leaks waiting to happen.

    For your particular scenario, this means that: