question
In Android development, tool classes are often implemented in a singleton mode, and tool classes are always used inevitably Context
, for example:
public class MySingleton {
private static volatile MySingleton instance;
private final Context ctx;
private MySingleton(Context context) {
ctx = context;
}
public static MySingleton getInstance(Context context) {
if (instance == null) {
synchronized (MySingleton.class) {
if (instance == null) {
instance = new MySingleton(context);
}
}
}
return instance;
}
}
Then it will appear:
Warning: Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)
Including Google's own example of using singleton mode will have this error...
Solution
This is because Activity
ordinary s don't necessarily have (actually are ) long Context
lifetimes and thus run the risk of memory leaks.final Context ctx
static MySingleton
After consulting a lot of information, the solution is mainly referred to here . The final code implementation is as follows:
public class MySingleton {
private static volatile MySingleton instance;
private final Context ctx;
private MySingleton(Context context) {
// 调用 getApplicationContext()
// 返回当前进程的单个全局应用程序对象的上下文。
// 这意味着 getApplicationContext() 返回的上下文将贯穿整个程序
ctx = context.getApplicationContext();
}
public static MySingleton getInstance(Context context) {
if (instance == null) {
synchronized (MySingleton.class) {
if (instance == null) {
instance = new MySingleton(context);
}
}
}
return instance;
}
}