问题
To be able to get app context anywhere in my app, I created App class like this:
public class App extends Application
{
private static Context mContext;
public static Context getContext()
{
return mContext;
}
@Override
public void onCreate()
{
super.onCreate();
mContext = this
}
}
It works and also it's used in many places in my app where I need to use context (for example, to load resources) and I am not able to inject any other context to use.
However, Android Studio throws warning this approach (static context fields) causes memory leak.
Do you have any idea how to avoid static context field, but get similar functionality?
回答1:
Never place static Context in your application since it will cause unexcepted memory leaks, however if you still want to use static Context in your application you can wrap the context in a WeakReference so change
private static Context mContext;
to
private static WeakReference<Context> mContext;
and on create change it to
mContext = new WeakReference<>(Context);
and finally get the Context using
public static Context getContext() {
return mContext.get();
}
if you want to research more about WeakRef use the link below, https://developer.android.com/reference/java/lang/ref/WeakReference
回答2:
Its not necessary use static for access context ,you can use get context ,get application context or get activity any where.
as far as possible you should avoid from passing context.
like this in fragments :DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getContext(), layoutManager.getOrientation());
and in this (if the OP wanted to use Context in where the class does not host a Context method) case you can pass context without define it as a static. for example :
public class DashboardWalletSpinnerAdapter extends ArrayAdapter<Wallet> {
private LayoutInflater mLayoutInflater;
private static final int CLOSE = 0;
private static final int OPEN = 1;
public DashboardWalletSpinnerAdapter(Context mContext, List<Wallet> walletList) {
super(mContext, R.layout.spinneritemclose_dashbaord, walletList);
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
来源:https://stackoverflow.com/questions/52848608/static-context-in-app-class-memory-leak