LeakCanary的使用

来源:互联网 发布:开淘宝网店花钱吗 编辑:程序博客网 时间:2024/05/20 04:08

LeakCanary是一个对Android和Java进行内存泄露检测的库
使用方法:首先在gradle中进行配置

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

接着自己定义一个Application

public class MyApplication 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;        }        refWatcher = LeakCanary.install(this);        // Normal app init code...    }    private RefWatcher refWatcher;    public static RefWatcher getRefWatcher(Context context) {        MyApplication application = (MyApplication) context.getApplicationContext();        return application.refWatcher;    }}

当然了这个Application要在manifest中设置成应用的Application

 android:name=".MyApplication"   

当需要检测某个对象是否泄露的时候也很简单

RefWatcher refWatcher = MyApplication.getRefWatcher(this);refWatcher.watch(object);

注意下调用这个方法的时机应该是object对象已经完成了任务,正常情况下应该被回收掉了,但是如果此时还有别的对象引用了object导致其不能被回收,就会造成内存泄露,LeakCanary就会检测到,并在通知栏提示

这里写图片描述

点击进去的话就会显示内存泄露的信息,即泄露的对象到底是被谁引用了

这里写图片描述

原创粉丝点击