关于Context内存泄漏问题,目前发现只是在单例模式下会出现,因此我只就单例模式出现的内存泄漏进行介绍 先上代码:`public class LoadImageHelper {
private static LoadImageHelper loadImageHelper;
private static Context mContext;
private LoadImageHelper() {
init();
}
public static LoadImageHelper getInstance(Context context) {
mContext = context;
if (loadImageHelper == null)
loadImageHelper = new LoadImageHelper();
return loadImageHelper;
}
}
大家看传入了一个context,看着好像没什么问题,其实如果传入的事Activity的context就出问题了,因为,单例模式的对象是随application销毁的,会一直存在,因此当将Activity的context传入,会导致该Activity的context一直被占用即使Activity退出,GC是不会被回收的,这就导致了内存泄漏,因此正确的方法是,传入Application的Context,因为application会一直存在,除非真个应用退出
public static LoadImageHelper getInstance(Context context) {
mContext =context.getApplicationContext();
if (loadImageHelper == null)
loadImageHelper = new LoadImageHelper();
return loadImageHelper;
}