Android |How to use Context in double-lock singleton mode to avoid warning hints of memory leaks

Article directory


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 Activityordinary s don't necessarily have (actually are ) long Contextlifetimes and thus run the risk of memory leaks.final Context ctxstatic 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;
    }
}

expand

Android design pattern (1) singleton pattern

The role of volatile in singleton mode double lock

Guess you like

Origin blog.csdn.net/Jormungand_V/article/details/126973173