LeakCanary源码学习笔记

  1. LeakCanary的使用:
    第一步:添加gradle配置:
    debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.6.3'
    releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.6.3'
    // Optional, if you use support library fragments:
    debugImplementation 'com.squareup.leakcanary:leakcanary-support-fragment:1.6.3'

第二步:在Application中进行初化:

class BaseApplication : Application() {
    var refWatcher: RefWatcher? = null

    companion object {
        lateinit var globalApp: BaseApplication
    }

    override fun onCreate() {
        super.onCreate()
        globalApp = this
        if (LeakCanary.isInAnalyzerProcess(this)) {
            return
        }
        refWatcher = LeakCanary.install(this);
    }
}

第三步:在Activity中使用

class MainActivity : AppCompatActivity() {
    var titleBarHelper: TitleBarHelper? = null;
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        titleBarHelper = TitleBarHelper(this);
        titleBarHelper!!.setTitle("设置标题")
        val dialog: CommonLoadingDialog = CommonLoadingDialog.buildDialog(this);
        dialogTv.setOnClickListener {
            dialog.showLoading()
        }
    }
    //注意:是在onDestroy方法中调用watch()方法
    override fun onDestroy() {
        super.onDestroy()
        BaseApplication.globalApp.refWatcher!!.watch(this)
    }
}

不要忘记在AndroidManifest.xml中配置BaseApplication 。

  1. 源码学习
    个人理解的原理:在Activity调用 onDestory方法时,把该Activity加入到指定队列(ReferenceQueue.java)中进行回收状态监听,从而判断是否有内存泄露。如果内存泄露了,则分析prof文件,把分析的结果通过Activity(DisplayLeakActivity.java)展示出来。我们就能直观地看到内存泄露的代码所在。
    本来想认真写下源码学习的,我的版本是1.6.3,在搜索资料时,发现网上已经有一篇非常全面的分析文章,分析是的1.6.2的,我就不敢卖弄了,直接贴上网址:https://blog.csdn.net/zyx67786110/article/details/84558953
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值