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?
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.
It turned out that in this particluar case I do not need whole resources as static member variable - I need just android.util.DisplayMetrics.
So I changed code to have
public class Utils{
private static DisplayMetrics mMetrics;
public static void init(Resources res) {
mMetrics=res.getDisplayMetrics();
}
That works fine, memory leak is not to be found anymore. Nevertheless, orginal question (static Resources variable) is still valid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With