首先在你项目app下的build.gradle中配置:
dependencies {
debugImplementation ‘com.squareup.leakcanary:leakcanary-android:1.6.2’
releaseImplementation ‘com.squareup.leakcanary:leakcanary-android-no-op:1.6.2’
// 可选,如果你使用支持库的fragments的话
debugImplementation ‘com.squareup.leakcanary:leakcanary-support-fragment:1.6.2’
}
复制代码
然后在你的Application中配置:
public class WanAndroidApp extends Application {
private RefWatcher refWatcher;
public static RefWatcher getRefWatcher(Context context) {
WanAndroidApp application = (WanAndroidApp) context.getApplicationContext();
return application.refWatcher;
}
@Override public void onCreate() {
super.onCreate();
if (LeakCanary.isInAnalyzerProcess(this)) {
// 1
return;
}
// 2
refWatcher = LeakCanary.install(this);
}
}
复制代码
在注释1处,会首先判断当前进程是否是Leakcanary专门用于分析heap内存的而创建的那个进程,即HeapAnalyzerService所在的进程,如果是的话,则不进行Application中的初始化功能。如果是当前应用所处的主进程的话,则会执行注释2处的LeakCanary.install(this)进行LeakCanary的安装。只需这样简单的几行代码,我们就可以在应用中检测是否产生了内存泄露了。当然,这样使用只会检测Activity和标准Fragment是否发生内存泄漏,如果要检测V4包的Fragment在执行完onDestroy()之后是否发生内存泄露的话,则需要在Fragment的onDestroy()方法中加上如下两行代码去监视当前的Fragment:
RefWatcher refWatcher = WanAndroidApp.getRefWatcher(_mActivity);
refWatcher.watch(this);
复制代码
上面的RefWatcher其实就是一个引用观察者对象,是用于监测当前实例对象的引用状态的。从以上的分析可以了解到,核心代码就是LeakCanary.install(this)这行代码,接下来,就从这里出发将LeakCanary一步一步进行拆解。
=================================================================
public static @NonNull RefWatcher install(@NonNull Application application) {
return refWatcher(application).listenerServiceClass(DisplayLeakService.class)
.excludedRefs(AndroidExcludedRefs.createAppDefaults().build())
.buildAndInstall();
}
复制代码
在install()方法中的处理,可以分解为如下四步:
-
1、refWatcher(application)
-
2、链式调用listenerServiceClass(DisplayLeakService.class)
-
3、链式调用excludedRefs(AndroidExcludedRefs.createAppDefaults().build())
-
4、链式调用buildAndInstall()
首先,我们来看下第一步,这里调用了LeakCanary类的refWatcher方法,如下所示:
public static @NonNull AndroidRefWatcherBuilder refWatcher(@NonNull Context context) {
return new AndroidRefWatcherBuilder(context);
}
复制代码
然后新建了一个AndroidRefWatcherBuilder对象,再看看AndroidRefWatcherBuilder这个类。
/** A {@link RefWatcherBuilder} with appropriate Android defaults. */
public final class AndroidRefWatcherBuilder extends RefWatcherBuilder {
…
AndroidRefWatcherBuilder(@NonNull Context context) {
this.context = context.getApplicationContext();
}
…
}
复制代码
在AndroidRefWatcherBuilder的构造方法中仅仅是将外部传入的applicationContext对象保存起来了。AndroidRefWatcherBuilder是一个适配Android平台的引用观察者构造器对象,它继承了RefWatcherBuilder,RefWatcherBuilder是一个负责建立引用观察者RefWatcher实例的基类构造器。继续看看RefWatcherBuilder这个类。
public class RefWatcherBuilder<T extends RefWatcherBuilder> {
…
public RefWatcherBuilder() {
heapDumpBuilder = new HeapDump.Builder();
}
…
}
复制代码
在RefWatcher的基类构造器RefWatcherBuilder的构造方法中新建了一个HeapDump的构造器对象。其中HeapDump就是一个保存heap dump信息的数据结构。
接着来分析下install()方法中的链式调用的listenerServiceClass(DisplayLeakService.class)这部分逻辑。