LeakCanary实现原理:
首先将Activity用弱引用(WeakReference)包装并绑定引用队列(ReferenceQueue),系统在gc的时候会优先回收弱引用,同时将要回收的引用放到引用队列中。所以只要判断引用队列中是否存在目标引用,就可以判断目标引用是否存在内存泄漏(如果存在则说明没有内存泄漏,反之则说明有内存泄漏)。
如何保证GC立即执行?
GcTrigger DEFAULT = new GcTrigger() {
@Override public void runGc() {
// Code taken from AOSP FinalizationTest:
// https://android.googlesource.com/platform/libcore/+/master/support/src/test/java/libcore/
// java/lang/ref/FinalizationTester.java
// System.gc() does not garbage collect every time. Runtime.gc() is
// more likely to perform a gc.
Runtime.getRuntime().gc();
enqueueReferences();
System.runFinalization();
}
private void enqueueReferences() {
// Hack. We don't have a programmatic way to wait for the reference queue daemon to move
// references to the appropriate queues.
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new AssertionError();
}
}
};
监测实现流程:
Application初始化 -> 注册ActivityLifecycleCallbacks ->在ActivityLifecycleCallbacks的onDestroy()中调用RefWatcher.watch()->watch()方法中判断是否存在内存泄漏,HeapDumper抓取dump文件并通过HeapAnalyzerService.runAnalysis分析-> 最后通过DisplayLeakService展示内存泄漏信息