本文主要是介绍LeakCanary源码学习笔记,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
- 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? = nullcompanion object {lateinit var globalApp: BaseApplication}override fun onCreate() {super.onCreate()globalApp = thisif (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 。
- 源码学习
个人理解的原理:在Activity调用 onDestory方法时,把该Activity加入到指定队列(ReferenceQueue.java)中进行回收状态监听,从而判断是否有内存泄露。如果内存泄露了,则分析prof文件,把分析的结果通过Activity(DisplayLeakActivity.java)展示出来。我们就能直观地看到内存泄露的代码所在。
本来想认真写下源码学习的,我的版本是1.6.3,在搜索资料时,发现网上已经有一篇非常全面的分析文章,分析是的1.6.2的,我就不敢卖弄了,直接贴上网址:https://blog.csdn.net/zyx67786110/article/details/84558953
这篇关于LeakCanary源码学习笔记的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!