OOM 是 Android 开辟中常见的问题,而内存泄漏往往是祸首祸首。
为了简单便利的检测内存泄漏,Square 开源了 LeakCanary ,它可以及时`测 Activity 是否产生了泄漏,一旦发明就会主动弹出提示及相干的泄漏信息供分析。
本文的目标是试图经由过程分析 LeakCanary 源率攀来商量它的 Activity 泄漏检测机制。
然后再回到膳绫擎的代码。
LeakCanary 应用方法
为了将 LeakCanary 惹人到我们的项目里,我们只须要做以下两步:
- dependencies {
- debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5.1'
- releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'
- testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'}public class ExampleApplication extends Application { @Override public void onCreate() { super.onCreate(); if (LeakCanary.isInAnalyzerProcess(this)) { // This process is dedicated to LeakCanary for heap analysis.
- // You should not init your app in this process.
- return;
- }
- LeakCanary.install(this);
- }
- }
可以看出,最症桨?酵是 LeakCanary.install(this); 这么一句话,正式开启了 LeakCanary 的大年夜门,将来它就会主动帮我们检测内存泄漏,并在产生泄漏是弹出通知信息。
大年夜 LeakCanary.install(this); 开端
下面我们来看下它做了些什么?
- 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) { if (isInAnalyzerProcess(application)) { return RefWatcher.DISABLED;
- }
- enableDisplayLeakActivity(application);
- HeapDump.Listener heapDumpListener = new ServiceHeapDumpListener(application, listenerServiceClass);
- RefWatcher refWatcher = androidWatcher(application, heapDumpListener, excludedRefs);
- ActivityRefWatcher.installOnIcsPlus(application, refWatcher); return refWatcher;
- }
常用的触发 gc 办法是 System.gc() ,那它能达到我们的请求吗?
可以如何来改革 LeakCanary 呢?
起首,我们先看最重要的部分,就是:
- RefWatcher refWatcher = androidWatcher(application, heapDumpListener, excludedRefs);
- ActivityRefWatcher.installOnIcsPlus(application, refWatcher);
师长教师成了一个 RefWatcher ,这个器械异常关键,大年夜名字可以看出,它是用来 watch Reference 的,也就是用来一个监控引用的对象。然后再把 refWatcher 和我们本身供给的 application 传入到 ActivityRefWatcher.installOnIcsPlus(application, refWatcher); 这句琅绫擎,持续看。
推荐阅读
Linux 用户可能经常碰到的一个问题是,机械有 16GB 内存之多,运行的过程也不多,然则剩下的 free 内存并不多,大年夜部分都被 buff 和 cache 占用了(比如下面我的 PC)。$ free -h >>>详细阅读
本文标题:带你学开源项目:LeakCanary-如何检测 Activity 是否泄漏
地址:http://www.17bianji.com/lsqh/35385.html
1/2 1