最近在看一个算比较大的android项目的源码,发现了一个很严重的问题,就是项目里使用单例模式,构造函数要传入Context做参数的类,基本上都存在内存泄露问题。

存在内存泄露问题的一些代码片段像下面这样:

Util.javapublic class Util {  private Context mContext;  private static Util sInstance;  private Util(Context context) {     this.mContext = context;  }  public static Util getInstance(Context context) {        if (sInstance == null) {            sInstance = new Util(context);        }       return sInstance;    }//other methods}

假设Activity A里使用Util类:

Util.getInstance(this);

代码大意就是这样,这样写的问题就是,在Activity A里使用Util类,传入的context 是 actvitiy-context。试想一下,当Activity A生命周期结束,但Util类里面却还存在A的引用 (mContext),这样Activity A占用的内存就一直不能回收,而A的对象也不会再被使用。本人写代码测试过,在A中调用了finish(),A的destroy()方法也被执行了,但其占用的内存,比如说,ImageView占用的内存,还是不能释放的。有兴趣的话,可以自己测试一下。

那么如何解决这个问题呢?在A中,可以用Util.getInstance(getApplicationContext()); 或Util.getInstance(getApplication());代替。

因为Application的生命周期是贯穿整个程序的,所以Util类持有它的引用,也不会造成内存泄露问题。

其实这个问题android官方文档的Resources目录下的一篇题为

Avoiding Memory Leaks

的文章已经提到过。

可以自己去了解具体。

In summary, to avoid context-related memory leaks, remember the following:

  • Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself)
  • Try using the context-application instead of a context-activity
  • Avoid non-static inner classes in an activity if you don't control their life cycle, use a static inner class and make a weak reference to the activity inside. The solution to this issue is to use a static inner class with ato the outer class, as done inand its W inner class for instance
  • A garbage collector is not an insurance against memory leaks

更多相关文章

  1. 一句话锁定MySQL数据占用元凶
  2. [Android(安卓)Memory] App调试内存泄露之Context篇(下)
  3. 内存分析与内存泄漏检测
  4. Android获取系统cpu信息,内存,版本,电量等信息
  5. 查看Android设备给每个应用分配的内存大小
  6. 关于 Android(安卓)中 Bitmap 的 ARGB_8888、ALPHA_8、ARGB_4444
  7. Android之旅[1] - Architecture
  8. android有效解决加载大图片内存溢出的问题
  9. [置顶] 如何分析Android的内存使用量

随机推荐

  1. android XMl Selector 图片背景点击和焦
  2. 导入第三方项目因gradle引起的不能运行问
  3. Android(安卓)StudioHttp协议GET连接
  4. android 可以控制速度的跑马灯
  5. 原著阅读 - Android(安卓)Programming Th
  6. numberPicker实现时间选择设置功能
  7. android写入数据库、读取sqlite中的图片
  8. Android语言和文化适配
  9. Automatically Mount Your Android(安卓)
  10. android 弹出层