1.在检查内存泄漏以前我们需要准备的是先了解内存泄漏是怎样形成的
详情请见:Android 关于内存泄漏和优化
2.看完以后,各位砖友应该基本了解了内容泄漏是怎么形成的了,那么接下来开始集成
3.首先导入依赖
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3' releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3'
4.在根目录下创建一个App 继承Application 写入下列代码
public static RefWatcher getRefWatcher(Context context) { App application = (App) context.getApplicationContext(); return application.refWatcher; } private RefWatcher refWatcher; @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); }
5.在MainActivity中写入
@Override protected void onDestroy() { super.onDestroy(); RefWatcher refWatcher = App.getRefWatcher(this); refWatcher.watch(this); }
6.大家千万别忘了在清单文件注册App 类
7.大家集成以后遇到的问题
集成完以后,大家运行完你的Demo后,会发现 没有任何反应!!! 就像什么都没有写一样 大家不要惊慌 是因为你这个Demo中并没有出现内存泄漏的情况!!! 在真实的项目中,接入完如果运行项目还是没有反应,那我就恭喜你了,你的代码写的很完美,没有出现内存泄漏的情况!!!