LeakCanary
参考:https://github.com/square/leakcanary/wiki/FAQ#how-does-it-work
https://blog.csdn.net/xinzhou201/article/details/78637700
GitHub上关于LeakCanary的原理:
RefWatcher.watch()
creates a KeyedWeakReference to the watched object.- Later, in a background thread, it checks if the reference has been cleared and if not it triggers a GC.
- If the reference is still not cleared, it then dumps the heap into a
.hprof
file stored on the file system. HeapAnalyzerService
is started in a separate process andHeapAnalyzer
parses the heap dump using HAHA.HeapAnalyzer
finds theKeyedWeakReference
in the heap dump thanks to a unique reference key and locates the leaking reference.HeapAnalyzer
computes the shortest strong reference path to the GC Roots to determine if there is a leak, and then builds the chain of references causing the leak.- The result is passed back to
DisplayLeakService
in the app process, and the leak notification is shown.
这个涉及到弱引用的概念,可以参考https://blog.csdn.net/mazhimazh/article/details/19752475, 其中关于四四种的概念和使用场景进行了清除的介绍。单拿弱引用来说,弱引用不管内存是否够用,在GC的是时候都会被回收,主要用于引用的对象有自己的生命周期,而我们又不想影响对象生命周期的情况下,用于检测Activity/Fragment的内存泄露再合适不过。