在 build.gradle
中加入引用,不一样的编译使用不一样的引用:java
dependencies {
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3'
}
在 Application
中:android
public class ExampleApplication extends Application { @Override public void onCreate() { super.onCreate(); LeakCanary.install(this); } }
使用 RefWatcher
监控那些本该被回收的对象。git
RefWatcher refWatcher = {...}; // 监控 refWatcher.watch(schrodingerCat);
LeakCanary.install()
会返回一个预约义的 RefWatcher
,同时也会启用一个 ActivityRefWatcher
,用于自动监控调用Activity.onDestroy()
以后泄露的 activity。github
public class ExampleApplication extends Application { public static RefWatcher getRefWatcher(Context context) { ExampleApplication application = (ExampleApplication) context.getApplicationContext(); return application.refWatcher; } private RefWatcher refWatcher; @Override public void onCreate() { super.onCreate(); refWatcher = LeakCanary.install(this); } }
使用 RefWatcher
监控 Fragment:app
public abstract class BaseFragment extends Fragment { @Override public void onDestroy() { super.onDestroy(); RefWatcher refWatcher = ExampleApplication.getRefWatcher(getActivity()); refWatcher.watch(this); } }
RefWatcher.watch()
建立一个 KeyedWeakReference 到要被监控的对象。ide
而后在后台线程检查引用是否被清除,若是没有,调用GC。gradle
若是引用仍是未被清除,把 heap 内存 dump 到 APP 对应的文件系统中的一个 .hprof
文件中。ui
在另一个进程中的 HeapAnalyzerService
有一个 HeapAnalyzer
使用HAHA 解析这个文件。this
得益于惟一的 reference key, HeapAnalyzer
找到 KeyedWeakReference
,定位内存泄露。spa
HeapAnalyzer
计算 到 GC roots 的最短强引用路径,并肯定是不是泄露。若是是的话,创建致使泄露的引用链。
引用链传递到 APP 进程中的 DisplayLeakService
, 并以通知的形式展现出来。