android开发笔记之内存泄漏检测工具leakcanary

这里写图片描述

leakcanary简单介绍

LeakCanary是GitHub上著名的开源组织Square贡献的一个内存泄漏自动检测工具。
优点:自动化发现内存泄漏;配置非常的简单。
补充一点:内存泄漏往往发生在,生命周期较长的对象,直接或间接的持有了生命周期较短的对象的强引用,导致生命周期较短的对象不能及时的释放。

leakcanary使用方法

leakcanary使用方法极其简单,我们可以查看一下github leakcanary的说明。

我们测试的版本为1.5.4:

github leakcanary上的使用方法介绍是极其的简单:

第一步:在Gradle中添加依赖(LeakCanary的非常好的一点是,在debug版本时才会检测,在release版本会跳过检测)

In your build.gradle:

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

第二步:在Application中初始化LeakCanary:

In your Application class:

import android.app.Application;
import com.squareup.leakcanary.LeakCanary;
p
ublic 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...
  }
}

第三步,在AndroidManifest.xml文件中修改应用的名字类:

    <application
        android:name="android.com.demo_01.ExampleApplication"

一个例子

定义一个测试类—TestLeakSingleton :

public class TestLeakSingleton {

    private TextView tv;
    private Context context;
    private static TestLeakSingleton singleton = null;

    public static TestLeakSingleton getInstance(Context context){
        if(singleton == null){
            singleton = new TestLeakSingleton(context);
        }
        return singleton;
    }

    private TestLeakSingleton(Context context){
        this.context = context;
    }

    public void setTvAppName(TextView tv){
        this.tv = tv;
        tv.setText(context.getString(R.string.app_name));
    }
}

新建一个简单的界面:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView = (TextView) findViewById(R.id.tv_appname);
        TestLeakSingleton.getInstance(this).setTvAppName(textView);
    }

}

生成APK,安装到手机上测试:

操作:
1,启动这个Activity
2,退出activity
3,重复以上二个操作

不一会,在通知栏出现了一个通知:

这里写图片描述

点击进去,如下显示:

这里写图片描述

参考资料

1.leakcanary
https://github.com/square/leakcanary
2.LeakCanary 使用一
http://m.blog.csdn.net/wangsongbin893603021/article/details/75007034

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hfreeman2008

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值