简介:
LeakCanary是一个开源的内存泄漏检查工具,使用简单,主要用来监测Activity和Fragment是否发生内存泄漏。如果发生内存泄漏,直接以引用链的形式展示出造成内存泄漏对象。
使用步骤
- 添加build.gradle依懒。
debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.6.3' releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.6.3' debugImplementation 'com.squareup.leakcanary:leakcanary-support-fragment:1.6.3'
2.在Application中初始化LeakCanary。
class CustomApplication:MainApplication() { override fun onCreate() { super.onCreate() if (! LeakCanary.isInAnalyzerProcess(this)) { LeakCanary.install(this); } } }
完成以上两步操作之后,当打开app运行时,如果Activity或Fragment发生内存泄漏,会以通知的形式展示出来。
源码分析
先通过流程图来看一下LeakCanary工作原理,如图所示:
LeakCanary初始化
1.在application中注册。
class CustomApplication:MainApplication() { override fun onCreate() { super.onCreate() if (! LeakCanary.isInAnalyzerProcess(this)) { //注册leakcanary LeakCanary.install(this); } } }
2.构建观察者RefWatcher。
public static RefWatcher install(Application application) { //构建观察者RefWatcher return refWatcher(application).listenerServiceClass(DisplayLeakService.class) .excludedRefs(AndroidExcludedRefs.createA