1、添加依赖
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
加在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中的日志锁定产生内存泄漏的位置进行处理