将 Context 作为参数传递给 Singleton class 中的方法会导致内存泄漏
Is passing Context as a parameter to a method in a Singleton class causes memory leak
我正在声明一个 Singleton class,我需要为此 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....
}
}
会不会导致内存泄露
可能,因为您不知道您将引用哪种 Context
。这样写会更安全:
this.mContext = context.getApplicationContext();
这样,您就可以确定 mContext
正在引用 Application
单例。
我正在声明一个 Singleton class,我需要为此 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....
}
}
会不会导致内存泄露
可能,因为您不知道您将引用哪种 Context
。这样写会更安全:
this.mContext = context.getApplicationContext();
这样,您就可以确定 mContext
正在引用 Application
单例。