检测内存泄漏常用工具之Leakcanary

来源:互联网 发布:网络安全技术保障方案 编辑:程序博客网 时间:2024/06/16 06:00

在遇到Leakcanary之前,排查Android开发时发生内存泄漏问题,真是蛋疼的要命,后来技术发烧友向我推荐了Leakcanary这款利器,我试着集成到开发项目中,不得了了:内存泄漏定位准确(比如持有static的强引用对象窗体结束后仍然未销毁),让我在解决时候有了一个明确的方向感。让我优雅的处理内存泄漏的排查和解决。感谢Square神器Leakcanary,github开源地址:https://github.com/square/leakcanary

集成方式也是很简单:

首先在build.gradle添加依赖:

dependencies {   debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5.4'   releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.4' }

然后再程序的Application中的onCreate()方法初始化操作:

public class ExampleApplication extends Application {  @Override public void onCreate() {    super.onCreate();    if (LeakCanary.isInAnalyzerProcess(this)) {      // This process is dedicated to LeakCanary for heap analysis.      // You should not init your app in this process.      return;    }    LeakCanary.install(this);    // Normal app init code...  }}

到这里就可以跑起来自己的项目了,当有内存泄漏的时候,Leakcanary会 显示定位到应用中发生内存泄漏的地方:

这里写图片描述

看到这图估计你就知道咋去处理问题啦~~


注意声明:
切记,当你的应用上线的时候记得关闭(注释)掉相关检测代码!