Activiyt的监控
注册监听Activity的生命周期(ActivityRefWatcher.install(Contex context, RefWatcher refWatcher),在onActivityDestroyed中执行:refWatcher.watch(activity),重点就是这个watch方法。
2. RefWatcher的设计
成员变量:
public static final RefWatcher DISABLED = new RefWatcherBuilder<>().build();
private final WatchExecutor watchExecutor;
private final DebuggerControl debuggerControl;
private final GcTrigger gcTrigger;
private final HeapDumper heapDumper;
private final HeapDump.Listener heapdumpListener;
private final HeapDump.Builder heapDumpBuilder;
private final Set<String> retainedKeys;
private final ReferenceQueue<Object> queue;
成员方法:
public void watch(Object watchedReference);
public void watch(Object watchedReference, String referenceName);
- 为每一次watch动作(出现Activity Destroyed的时候)创建一个Random UUID,作为key保存在retainedKeys中; 创建KeyedWeakReference,传入自己的ReferenceQueue变量queue。
然后调用:
watchExecutor.new Retryable() {
@Override
public Retryable.Result run() {
return ensureGone(reference, watchStartNanoTime);
}
});
- 核心方法就是RefWatcher的ensureGone()方法。
① 判断监控的reference是否已经变为弱可达(weakly reachable), 如果变为弱可达, 则表示该对象已经正常回收, 清除retainedKeys;
② 如果retainedKeys已经不包含reference, 表示已经被正常回收掉, 返回;
③ 手动运行一次GC
④ 再次check一下queue,如果reference还在retainedKeys中,表示存在内存泄露,构建HeapDump
对象,回调heapdumpListener.analyze(heapDump)。
网友评论