Android 内存泄漏分析工具LeakCanary

从事Android 开发经常会碰到OOM问题,除了MAT工具分析,今天介绍一个非常好用的开源工具:LeakCanary 

地球人都在用,还不赶快试试! 开源网址 https://github.com/square/leakcanary 

1. 对Activity对象进行监控

//在项目的build.gradle文件添加:
 dependencies {
   debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3'
   releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3'
 }
//在Application类添加:
public class ExampleApplication extends Application {

  @Override public void onCreate() {
    super.onCreate();
    LeakCanary.install(this);
  }
}

这样就万事俱备了。在 debug build 中如果检测到某个 activity 有内存泄露,LeakCanary 就是自动地显示一个通知。


2.使用 RefWatcher 监控那些本该被回收的对象:例如对Fragment监控 

事实上,LeakCanary.install() 会返回一个预定义的 RefWatcher,同时也会启用一个 ActivityRefWatcher,用于自动监控调用 Activity.onDestroy() 之后泄露的 activity。 使用这个预定义的 RefWatcher 可以用来监控 Fragment:

public abstract class BaseFragment extends Fragment {

  @Override 
  public void onDestroy() {
    super.onDestroy();
    RefWatcher refWatcher = ExampleApplication.getRefWatcher(getActivity());
    refWatcher.watch(this);
  }
}

public class ExampleApplication extends Application {
  private RefWatcher refWatcher;

  @Override 
  public void onCreate() {
    super.onCreate();
    refWatcher = LeakCanary.install(this);
  }

  public static RefWatcher getRefWatcher(Context context) {
    ExampleApplication application = (ExampleApplication) context.getApplicationContext();
    return application.refWatcher;
  }
}
3. LeakCanary的工作机制:
(1)RefWatcher.watch() 创建一个 KeyedWeakReference 到要被监控的对象。
(2)然后在后台线程检查引用是否被清除,如果没有,调用GC。
(3)如果引用还是未被清除,把 heap 内存 dump 到 APP 对应的文件系统中的一个 .hprof 文件中。
(4)在另外一个进程中的 HeapAnalyzerService 有一个 HeapAnalyzer 使用HAHA 解析这个文件。
(5)得益于唯一的 reference key, HeapAnalyzer 找到 KeyedWeakReference,定位内存泄露。
(6)HeapAnalyzer 计算 到 GC roots 的最短强引用路径,并确定是否是泄露。如果是的话,建立导致泄露的引用链。
(7)引用链传递到 APP 进程中的 DisplayLeakService, 并以通知的形式展示出来。
4. 有时,leakCanary不够,你需要通过 MAT 或者 YourKit 深挖 dump 文件。通过以下方法,你能找到问题所在:

(1). 查找所有的 com.squareup.leakcanary.KeyedWeakReference 实例。
(2). 检查 key 字段
(3). Find the KeyedWeakReference that has a key field equal to the reference key reported by LeakCanary.
(4). 找到 key 和 和 logcat 输出的 key 值一样的 KeyedWeakReference。
(5). referent 字段对应的就是泄露的对象。
(6). 剩下的,就是动手修复了。最好是检查到 GC root 的最短强引用路径开始。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值