使用LeakCanary进行项目内存泄漏处理

来源:互联网 发布:淘宝网兜售野鸟 编辑:程序博客网 时间:2024/06/05 01:56

1、添加依赖

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


2、在application中进行配置

加在onCreate()前

 //初始化LeakCanary    public static RefWatcher getRefWatcher(Context context) {        MyApplication application = (MyApplication) context.getApplicationContext();        return application.refWatcher;    }    private RefWatcher refWatcher;
 3、在onCreate()中添加代码

//LeakCanary初始化        if (LeakCanary.isInAnalyzerProcess(this)) {            return;        }        refWatcher=LeakCanary.install(this);
4、在BaseActivity中onDestory()中添加代码

 @Override    protected void onDestroy() {        super.onDestroy();        RefWatcher refWatcher = MyApplication.getRefWatcher(this);        refWatcher.watch(this);    }
项目中如果有Fragemnt的话要在BaseFragment中添加代码如下

 @Override    public void onDestroy() {        super.onDestroy();        RefWatcher refWatcher = MyApplication.getRefWatcher(getActivity());        refWatcher.watch(this);    }

OK下面就是运行项目进行检测了,如果检测到内存泄露的话,会弹出通知,进行提示,通过查看leakCanary中的日志锁定产生内存泄漏的位置进行处理




0 0
原创粉丝点击