监控 Activity 泄露
build.gradle
dependencies {
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
}
或者
compile 'com.squareup.leakcanary:leakcanary-android:1.4-beta2'
在项目里添加一个类叫MyApplication 继承自Application ,并在其中“安装”
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
LeakCanary.install(this);
}
}
记得把它作为 android:name 配到 AndroidManifest.xml 的 Application 节点下
监控Fragment泄漏
使用RefWatcher监控
- 此类的对象的获取方式:RefWatcher refWatcher=LeakCanary.install(this);
public class MyApplication extends Application {
public static RefWatcher refWatcher;
@Override
public void onCreate() {
super.onCreate();
refWatcher = LeakCanary.install(this);
}
}
- 然后,在需要检测Fragment回收的地方,加入refWatcher.watch(this);
public abstract class BaseFragment extends Fragment {
@Override
public void onDestroy() {
super.onDestroy();
RefWatcher refWatcher = MyApplication.refWatcher;
refWatcher.watch(this);
}
}
监控其他泄漏
RefWatcher refWatcher = MyApplication.refWatcher;
refWatcher.watch(someObjNeedGced);
- someObjNeedGced标识我们需要监控的对象,当 someObjNeedGced 还在内存中时,就会在 logcat 里看到内存泄漏的提示。
LeakCanary 的机制如下
- RefWatcher.watch() 会以监控对象来创建一个 KeyedWeakReference 弱引用对象
- 在 AndroidWatchExecutor 的后台线程里,来检查弱引用已经被清除了,如果没被清除,则执行一次 GC
- 如果弱引用对象仍然没有被清除,说明内存泄漏了,系统就导出 hprof 文件,保存在 app 的文件系统目录下
- HeapAnalyzerService 启动一个单独的进程,使用 HeapAnalyzer 来分析 hprof 文件。它使用另外一个开源库 HAHA。
- HeapAnalyzer 通过查找 KeyedWeakReference 弱引用对象来查找内在泄漏
- HeapAnalyzer 计算 KeyedWeakReference 所引用对象的最短强引用路径,来分析内存泄漏,并且构建出对象引用链出来。
- 内存泄漏信息送回给 DisplayLeakService,它是运行在 app 进程里的一个服务。然后在设备通知栏显示内存泄漏信息。
网友评论