React Native 周报Android经验和架构Android开发经验谈

解读LeakCanary-开篇

2016-07-21  本文已影响302人  璟龙

最近一直在学习LeakCanary这个库,大神的库果然是学习的好资料,通过这个库学习了很多开发中学不到的知识,打算写一系列文章对自己的学习做一个总结。

什么是LeakCanary

引用README中的介绍:
A memory leak detection library for Android and Java.

“A small leak will sink a great ship.”
-Benjamin Franklin

项目结构

项目结构图

使用项目

依赖

我们可以参考sample的依赖

dependencies { 
   debugCompile project(':leakcanary-android') 
   releaseCompile project(':leakcanary-android-no-op');
}

在debug模式下,引入正常版本,在release模式下引入no-op版本。

注入到项目中

public class ExampleApplication extends Application {

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

看看android和android-no-op的区别

android module中

public final class LeakCanary {

  public static RefWatcher install(Application application) {
    return install(application, DisplayLeakService.class,
        AndroidExcludedRefs.createAppDefaults().build());
  }

  public static RefWatcher install(Application application,
      Class<? extends AbstractAnalysisResultService> listenerServiceClass,
      ExcludedRefs excludedRefs) {
    ...
    RefWatcher refWatcher = androidWatcher(application, heapDumpListener, excludedRefs);
    ...
    return refWatcher;
   }

  public static RefWatcher androidWatcher(Context context, HeapDump.Listener heapDumpListener,
      ExcludedRefs excludedRefs) {
    ...
    return new RefWatcher(executor, debuggerControl, GcTrigger.DEFAULT, heapDumper,
        heapDumpListener, excludedRefs);
  }
}


返回的RefWatcher能够正常的监测对象。

android-no-op module中

public final class LeakCanary {

  public static RefWatcher install(Application application) {
    return RefWatcher.DISABLED;
  }
}

public final class RefWatcher {

  public static final RefWatcher DISABLED = new RefWatcher();

  private RefWatcher() {
  }

  public void watch(Object watchedReference) {
  }

  public void watch(Object watchedReference, String referenceName) {
  }
}

返回的RefWatcher中的watch方法都是空方法,不会监测对象。

上一篇 下一篇

猜你喜欢

热点阅读