android开发中单例造成的内存泄漏原因及解决方案

有一个单例是这样的:

public class SingleTon { 

    private static SingleTon singleTon; 

    private Context context; 

    private SingleTon(Context context) { 
        this.context = context; 
    } 

    public static SingleTon getInstance(Context context) { 
        if (singleTon == null) { 
            synchronized (SingleTon.class) { 
                if (singleTon == null) { 
                    singleTon = new SingleTon(context); 
                } 
            } 
        } 
        return singleTon; 
    } 

} 
这是单例模式饿汉式的双重校验锁的写法,这里的 singleTon 持有 Context 对象,如果 Activity 中调用 getInstance 方法并传入 this 时,singleTon 就持有了此 Activity 的引用,当退出 Activity 时,Activity 就无法回收,造成内存泄漏,所以应该修改它的构造方法:

private SingleTon(Context context) { 
    this.context = context.getApplicationContext(); 
}
通过 getApplicationContext 来获取 Application 的 Context,让它被单例持有,这样退出 Activity 时,Activity 对象就能正常被回收了,而 Application 的 Context 的生命周期和单例的生命周期是一致的,所有再整个 App 运行过程中都不会造成内存泄漏。


你可能感兴趣的:(android开发中单例造成的内存泄漏原因及解决方案)