1.初始化
加入依赖:com.squareup.leakcanary:leakcanary-android
他初始化是内部定义了一个ContentProvider然后再ContentProvider进行初始化的,
<provider
android:name="leakcanary.internal.AppWatcherInstaller$MainProcess"
android:enabled="@ref/0x7f040007"
android:exported="false"
android:authorities="com.xfhy.allinone.leakcanary-installer" />
<!--这里的@ref/0x7f040007对应的是@bool/leak_canary_watcher_auto_install-->
class AppWatcherInstaller : ContentProvider() {
override fun onCreate(): Boolean {
val application = context!!.applicationContext as Application
AppWatcher.manualInstall(application)
return true
}
}
这里需要注意的是app启动的时候会自动初始化ContentProvider,执行的时机会比Applicaiton的create还早。
- 抓取泄露的时机
通过Applicaiton 的registerActivityLifecyclcallbacks() 注册生命周期监听,然后再Destroyed()进行检测对象是否泄露。
实现的要点:
- 当一个对象要回收时生成一个唯一的key,把他封装到KeyedWeakReference中,并传入自定义的ReferenceQueue。
- 将Key和KeyedWeakReference放到一个map中去。
- 触发GC的时候,ReferenceQueque中的KeyedWeakReference全部移除,并根据这些KeyedWeakReference的key将map中的KeyWeakReference也移除掉。
- 如果map中的还有KeyedWeakReference剩余,那么就是有内存泄露了。
- 将内存泄露的对象分析引用链保存数据。