问题
I'm declaring a Singleton class where I need to pass context parameter for one of the methods in this class
public class MySingleton() {
Private Context mContext;
Private static MySingleton mInstance;
public static MySingleton mInstance() {
if (mInstance == null) {
mInstance = new MySingleton();
}
return mInstance;
}
public void myMethod(Context context)
{
this.mContext = context;
// write your code here....
}
}
will this cause a memory leak.
回答1:
It could, as you do not know what sort of Context
you will be referencing. It would be safer to write:
this.mContext = context.getApplicationContext();
This way, you are certain that mContext
is referencing the Application
singleton.
来源:https://stackoverflow.com/questions/56102382/is-passing-context-as-a-parameter-to-a-method-in-a-singleton-class-causes-memory