Search code examples
javaandroidandroid-activitystaticsharedpreferences

Static reference with a Context field will make an Activity to never be GC? Using shared preferences instead?


I have a static reference to an object that has a Context field into an activity. This is activity is pretty much a container for a WebView and it's reachable with the use of intent-filter. In other words, links can be opened directly inside my app.

Using instance variables would be pretty much pointless since the Activity gets destroyed when no longer has focus so I am using static instances for a boolean that is works as an option chooser and an object (with a Context field) that needs to perform work

   static boolean autoTrain = false;
   static AutoTrain autoTrain = new AutoTrain(getApplicationContext(),string);

But Android Studio is warning me:

Do not place Android context classes in static fields (static reference to AutoWalk2 which has field context pointing to Context); this is a memory leak Non-static inner classes have an implicit reference to their outer class. If that outer class is for example a Fragment or Activity, then this reference means that the long-running handler/loader/task will hold a reference to the activity which prevents it from getting garbage collected. Similarly, direct field references to activities and fragments from these longer running instances can cause leaks. ViewModel classes should never point to Views or non-application Contexts.

Usually I would have done this work inside a service but I would rather avoid using a Service and do everything inside my browser activity.

Could I use SharedPreferences to save both the boolean and the AutoTrain instead of using static references? SharedPreferences allows only primitives as far as I know but I think with google-gson one can save also objects. Although I am not sure how this will impact efficiency (speed in particular).


Solution

  • Your AutoTrain class presumably is declared to take a Context. Change that to take an Application to avoid this warning.

    You might also consider switching from raw static fields to using dependency inversion frameworks (Dagger/Hilt, or things like Koin if someday you move to Kotlin).

    SharedPreferences allows only primitives as far as I know but I think with google-gson one can save also objects

    Not if AutoTrain holds a reference to a Context or other data that cannot be represented in JSON.