Search code examples
androidmemory-leaksresource-leakeclipse-memory-analyzer

Android memory leak on static Resource member variable?


Is it safe to have static reference to private static Resources mRes; in my Utils class, initalized as follows?

public static void init(Resources res) {
    mRes = res;
}
.. later in activity
Utils.init(getContext().getResources());

It seems to me it causes memory leak (log from Eclipse Memory Analyzer below)

mOuterContext android.app.ContextImpl 
'- mContext android.content.res.Resources
  |- mRes class com.github.mikephil.charting.utils.Utils
  |- mResources android.app.LoadedApk
  |- mResources android.app.ContextImpl
  |- this$0 android.content.res.Resources$Theme
  |  '- referent java.lang.ref.FinalizerReference
  |     '- next java.lang.ref.FinalizerReference
  |        '- next java.lang.ref.FinalizerReference

Are there safe ways to get reference to Resources class, that is not leaking whole activity?


Solution

  • Here is a solution, use a static reference of your Application Context, held by your Application

    public class MyApplication extends Application
    {
        private static Context context;
    
        public static Resources getResourcesStatic()
        {
             return context.getResources();
        }
    
        @Override
        public void onCreate()
        {
            super.onCreate();
            this.context = this.getApplicationContext();
        }
    }
    

    Now just call MyApplication.getResourcesStatic() to access your resources wherever you are.