浅析Android内存泄漏检测工具LeakCanary

LeakCanary
A memory leak detection library for Android and Java.

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

浅析Android内存泄漏检测工具LeakCanary_第1张图片
image.png

如何使用?

  1. build.gradle添加LeakCanary库:
dependencies {
  debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.5.4'
  releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.4'
}

2.在Application初始化LeakCanary:

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);
    // Normal app init code...
  }
}

以上两步操作完之后,当activity发生内存泄漏的时候(debug模式下),LeakCanary会自动弹出通知。

如果想在单元测试的时候,禁用LeakCanary,可以在build.gradle添加如下代码

// Ensure the no-op dependency is always used in JVM tests.
configurations.all { config ->
  if (config.name.contains('UnitTest')) {
    config.resolutionStrategy.eachDependency { details ->
      if (details.requested.group == 'com.squareup.leakcanary' && details.requested.name == 'leakcanary-android') {
        details.useTarget(group: details.requested.group, name: 'leakcanary-android-no-op', version: details.requested.version)
      }
    }
  }
}

If you want to also disable leak detection in instrumentation tests(底层的Andr​​oid测试API), add || config.name.contains('AndroidTest') to the if check above.

因为LeakCanary默认只监测Activity,如何使用LeakCanary检测fragment是否存在内存泄漏?
使用RefWatcher来观察fragment的内存使用,如下:

public abstract class BaseFragment extends Fragment {

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

原理分析

  1. ActivityRefWatcher中,注册Activity生命周期监听接口,当Activity onDestroy()被调用时,将当前Activity加入内存泄漏监听队列;
private final Application.ActivityLifecycleCallbacks lifecycleCallbacks =
            new Application.ActivityLifecycleCallbacks() {
                @Override
                public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                }

                @Override
                public void onActivityStarted(Activity activity) {
                }

                @Override
                public void onActivityResumed(Activity activity) {
                }

                @Override
                public void onActivityPaused(Activity activity) {
                }

                @Override
                public void onActivityStopped(Activity activity) {
                }

                @Override
                public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
                }

                @Override
                public void onActivityDestroyed(Activity activity) {
                    ActivityRefWatcher.this.onActivityDestroyed(activity);
                }
            };

    public void watchActivities() {
        // Make sure you don't get installed twice.
        stopWatchingActivities();
        application.registerActivityLifecycleCallbacks(lifecycleCallbacks);
    }

  public void stopWatchingActivities() {
    application.unregisterActivityLifecycleCallbacks(lifecycleCallbacks);
  }

leakcanary只在application onCreate时调用了LeakCanary.install(this),它是怎么监控activity的呢?主要靠的 application.registerActivityLifecycleCallbacks(listener),app中的每个activity的每一个生命周期都会回调listener中相关方法,从而leakcanary在生命周期相关方法中能取到Activity,注意注册Activity生命周期监听接口只在Android 4.0以上支持。

  1. RefWatcher中,watch方法将对象用WeakReference引起来,监听对象是否内存泄漏。
  • leakcanary 的watch流程是在主线程空闲时,delay 5秒后检查对象有没有被回收,其中空闲时执行check是用的IdleHandler。
  • 判断一个对象有没有被回收是用的WeakReference与ReferenceQuene, 使用WeakReference(T referent, ReferenceQueue queue) 构造方法构造WeakReference时,如果这个WeakReference连接的对象被回收的话,系统会将WeakReference put进 ReferenceQuene,因此,如果ReferenceQuene中有哪个WeakReference,则表示这个WeakReference弱链接的对象已被回收。

主动GC,采用Runtime.getRuntime().gc()(对比System.gc()的优点是能保证及时触发GC),同时GC后等待100ms,等待Java虚拟机把这个弱引用加入ReferenceQueue,参考GcTrigger类。

判断内存是否被回收,没有被回收GC一次后再判断是否被回收,任然没有被回收则会通过Debug.dumpHprofData() 生成heap file,然后在service中通过haha(com.squareup.haha) 开源工具类进行文件分析,分析到强引用最短路径后,发送到UI线程弹出对话框。

  1. dump文件分析,HeapAnalyzer类
    基于Square开源的haha库,专用于分析Android heap dump文件,

相关文档
LeakCanary官方github地址
LeakCanary常见问题
haha库

你可能感兴趣的:(浅析Android内存泄漏检测工具LeakCanary)