Android 在Coding中防止内存泄漏——LeakCanary

前言

Android开发中内存泄漏的问题一直是比较头疼的问题,因为它发生了也很难被发现,在我们不知情的情况下也就没办法去修复这个问题。
LeakCanary的开源给我们一个简便的解决方案。

一、初始化

1.配置依赖:

    debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3.1'
    releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3.1'

2.在Application中初始化:

public class MyApplication extends Application {
    private static MyApplication instance;
    private RefWatcher mRefWatcher;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        mRefWatcher = !LeakCanary.isInAnalyzerProcess(this) ?  LeakCanary.install(this) : RefWatcher.DISABLED;
    }

    public static MyApplication getInstance() {
        return instance;
    }

    public static RefWatcher getRefWatcher() {
        return getInstance().mRefWatcher;
    }

}

二、检测

在BaseActivity中的OnDestory()中加入检测方法:

 @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.getRefWatcher().watch(this);
    }

然后就可以模拟一个内存泄漏的例子来试试看了。

  private Handler mHandler = new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //模拟内存泄露
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {

            }
        }, 3 * 60 * 1000);
    }

这个例子是Activity试图销毁时,仍被handler隐式持有,所以无法销毁引起内存泄漏。

三、获取泄漏信息

1.首先会有一个Toast弹出。

2.桌面上会有一个对应的Leaks App生成:

3.等待一会之后,在通知栏中会有一个notifacation出现:

4.点击这个notification会跳转到新生成的那个Leaks中去

这里就会有内存泄漏的信息了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值