主要作用创建了一个RefWatcher对象并返回,这个方法里面有两个比较重要的方法我们看下
ActivityRefWatcher.install(context, refWatcher)和FragmentRefWatcher.Helper.install(context, refWatcher);
(5) ActivityRefWatcher.install(context, refWatcher);
public static void install(Context context, RefWatcher refWatcher) {
Application application = (Application) context.getApplicationContext();
ActivityRefWatcher activityRefWatcher = new ActivityRefWatcher(application, refWatcher);
//为当前Application注册了所有Activity的生命周期的回调
application.registerActivityLifecycleCallbacks(activityRefWatcher.lifecycleCallbacks);
}
private final Application.ActivityLifecycleCallbacks lifecycleCallbacks =
new ActivityLifecycleCallbacksAdapter() {
@Override public void onActivityDestroyed(Activity activity) {
//当Activity销毁时调用refWathcer的watch方法观察这个对象
refWatcher.watch(activity);
}
};
(6) FragmentRefWatcher.Helper.install(context, refWatcher);
public static void install(Context context, RefWatcher refWatcher) {
//创建一个集合
List fragmentRefWatchers = new ArrayList<>();
//如果当前API版本大于26,创建一个AndroidOFragmentRefWatcher对象加入到集合中
if (SDK_INT >= O) {
fragmentRefWatchers.add(new AndroidOFragmentRefWatcher(refWatcher));
}
try {
//找到SupportFragmentRefWatcher这个类
Class<?> fragmentRefWatcherClass = Class.forName(SUPPORT_FRAGMENT_REF_WATCHER_CLASS_NAME);
//找到它的构造方法
Constructor<?> constructor =
fragmentRefWatcherClass.getDeclaredConstructor(RefWatcher.class);
//创建SupportFragmentRefWatcher实例,并添加到集合中
FragmentRefWatcher supportFragmentRefWatcher =
(FragmentRefWatcher) constructor.newInstance(refWatcher);
fragmentRefWatchers.add(supportFragmentRefWatcher);
} catch (Exception ignored) {
}
if (fragmentRefWatchers.size() == 0) {
return;
}
Helper helper = new Helper(fragmentRefWatchers);
Application application = (Application) context.getApplicationContext();
application.registerActivityLifecycleCallbacks(helper.activityLifecycleCallbacks);
}
这个方法的作用是当当前API版本大于26的时候,在Activity销毁是它会调用AndroidOFragmentRefWatcher的watchFragments方法观察当前Activity中的所有销毁的Fragments。也就是说如果当前API版本是大于26的,我们不需要在在Fragment的onDestory方法中自己调用RefWatcher的watch方法了。
下面我们来分析RefWatcher的watch方法,这个方法是LeakCanary的核心逻辑所在,我们一起来看看吧。
3.RefWatcher.watch();
public void watch(Object watchedReference) {
watch(watchedReference, “”);
}
public void watch(Object watchedReference, String referenceName) {
if (this == DISABLED) {
return;
}
checkNotNull(watchedReference, “watchedReference”);
checkNotNull(referenceName, “referenceName”);
//获取时间,纳秒级别
final long watchStartNanoTime = System.nanoTime();
//生成一个随机数作为key
String key = UUID.randomUUID().toString();
//retainedKeys是一个Set集合,存储所有的key
retainedKeys.add(key);
//使用KeyedWeakReference包装当前传过来的引用,代指Activity和Fragment
//注意了这里传了一个queue,即ReferenceQueue,所以如果KeyedWeakReference引用的Activity或者
//Fragment即将被销毁时,就会向这个queue中添加reference这个引用对象。
final KeyedWeakReference reference =
new KeyedWeakReference(watchedReference, key, referenceName, queue);
ensureGoneAsync(watchStartNanoTime, reference);
}
4.ensureGoneAsync()
private void ensureGoneAsync(final long watchStartNanoTime, final KeyedWeakReference reference) {
watchExecutor.execute(new Retryable() {
@Override public Retryable.Result run() {
return ensureGone(reference, watchStartNanoTime);
}
});
}
这里主要就是调用watchExecutor的execute添加了一个Retryable任务,有点类似与线程池。这边的watchExecutor是通过RefWathcer的构造方法传过来的。通过上面的分析,我们知道在一开始创建了一个AndroidRefWatcherBuilder对象,它会调用的buildAndInstall方法,这个方法中我们调用了build()方法创建了RefWatcher对象,现在我们去看看这个RefWathcer是怎么创建的。
5.build()
public final RefWatcher build() {
if (isDisabled()) {
return RefWatcher.DISABLED;
}
if (heapDumpBuilder.excludedRefs == null) {
heapDumpBuilder.excludedRefs(defaultExcludedRefs());
}
HeapDump.Listener heapDumpListener = this.heapDumpListener;
if (heapDumpListener == null) {
heapDumpListener = defaultHeapDumpListener();
}
DebuggerControl debuggerControl = this.debuggerControl;
if (debuggerControl == null) {
debuggerControl = defaultDebuggerControl();
}
HeapDumper heapDumper = this.heapDumper;
if (heapDumper == null) {
//调用的是AndroidRefWatcherBuilder中的方法。所以这里创建的是一个AndroidHeapDumper对象
heapDumper = defaultHeapDumper();
}
WatchExecutor watchExecutor = this.watchExecutor;
if (watchExecutor == null) {
//调用的是AndroidRefWatcherBuilder中的方法。所以这里创建的是一个AndroidWatchExecutor对象
watchExecutor = defaultWatchExecutor();
}
GcTrigger gcTrigger = this.gcTrigger;
if (gcTrigger == null) {
//创建的是GcTrigger DEFAULT这个对象
gcTrigger = defaultGcTrigger();
}
if (heapDumpBuilder.reachabilityInspectorClasses == null) {
heapDumpBuilder.reachabilityInspectorClasses(defaultReachabilityInspectorClasses());
}
return new RefWatcher(watchExecutor, debuggerControl, gcTrigger, heapDumper, heapDumpListener,
heapDumpBuilder);
}
这里注意了,AndroidRefWatcherBuilder类中没用实现build方法,所有是调用父类RefWatcherBuilder中的build方法,但是AndroidRefWatcherBuilder实现了defaultWatchExecutor,defaultHeapDumpListener这些方法,所以这些方法应该调用的是AndroidRefWatcherBuilder中的,而不是RefWatcherBuilder的。
6.AndroidWatchExecutor.execute()
通过5的分析我们知道RefWatcher中的watchExecutor对象其实是AndroidWatchExecutor类型的,下面我们来看看它的execute方法做了什么事。
@Override public void execute(Retryable retryable) {
//如果当前线程是主线程
if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
waitForIdle(retryable, 0);
} else {
postWaitForIdle(retryable, 0);
}
}
我们看到,这里分了两种情况去做处理。如果当前线程是主线程调用 waitForIdle(retryable, 0);否则调用postWaitForIdle(retryable, 0);。其实不管怎么样最终调用的都是waitForIdle这个方法。
1.waitForIdle(retryable, 0);
private void waitForIdle(final Retryable retryable, final int failedAttempts) {
//向主线程的消息队列中里添加了一个对象
//当我们注册了IdleHandler的时候,当主线程空闲时,会发送一个空闲消息来执行IdleHandler中的回调
//注意了,queueIdle这个返回为false是,表示只会执行一次,如果为true代表,如果主线程每次空闲时都会
//执行这个方法
Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
@Override public boolean queueIdle() {
//当主线程空闲时调用postToBackgroundWithDelay方法
postToBackgroundWithDelay(retryable, failedAttempts);
return false;
}
});
}
private void postToBackgroundWithDelay(final Retryable retryable, final int failedAttempts) {
long exponentialBackoffFactor = (long) Math.min(Math.pow(2, failedAttempts), maxBackoffFactor);
long delayMillis = initialDelayMillis * exponentialBackoffFactor;
//backgroundHandler是一个与异步线程绑定的Handler,我们可以看下AndroidWatchExecutor的构造方法中
//创建了一个HandlerThread,自己内部构建了一个异步的消息循环
//所以retryable.run()方法是执行在异步线程中的
backgroundHandler.postDelayed(new Runnable() {
@Override public void run() {
Retryable.Result result = retryable.run();
if (result == RETRY) {
postWaitForIdle(retryable, failedAttempts + 1);
}
}
}, delayMillis);
}
7.retryable.run() ->ensureGone
上面分析了那么多,其实这里才是我们的主要逻辑,我们先把涉及到的关键代码,贴出来,一步步来分析。
@SuppressWarnings(“ReferenceEquality”) // Explicitly checking for named null.
Retryable.Result ensureGone(final KeyedWeakReference reference, final long watchStartNanoTime) {
long gcStartNanoTime = System.nanoTime();
long watchDurationMs = NANOSECONDS.toMillis(gcStartNanoTime - watchStartNanoTime);
//如果对象GC时被回收了,就移除retainedKeys中对应的key值
removeWeaklyReachableReferences();
if (debuggerControl.isDebuggerAttached()) {
// The debugger can create false leaks.
return RETRY;
}
//如果retainedKeys还存在观察对象的key值代表没有被回收
if (gone(reference)) {
return DONE;
}
//第一次检查没有被回收手动触发GC
gcTrigger.runGc();
//GC完毕之后再去检查
removeWeaklyReachableReferences();
//如果GC后retainedKeys还存在观察对象的key。则表示发生了内存泄漏。
if (!gone(reference)) {
long startDumpHeap = System.nanoTime();
long gcDurationMs = NANOSECONDS.toMillis(startDumpHeap - gcStartNanoTime);
//dump生成文件
File heapDumpFile = heapDumper.dumpHeap();
if (heapDumpFile == RETRY_LATER) {
// Could not dump the heap.
return RETRY;
}
long heapDumpDurationMs = NANOSECONDS.toMillis(System.nanoTime() - startDumpHeap);
//创建了HeapDump对象
HeapDump heapDump = heapDumpBuilder.heapDumpFile(heapDumpFile).referenceKey(reference.key)
.referenceName(reference.name)
.watchDurationMs(watchDurationMs)
.gcDurationMs(gcDurationMs)
.heapDumpDurationMs(heapDumpDurationMs)
.build();
//回调ServiceHeapDumpListener的analyze方法,然后调用HeapAnalyzerService.runAnalysis的静态方法
//启动自身去分析HeapDump,使用HaHa库。不在做分析,感兴趣的朋友可以自己去研究研究。
heapdumpListener.analyze(heapDump);
}
return DONE;
}
private boolean gone(KeyedWeakReference reference) {
//判断是否还存在当前引用的key
//如果存在代表没有被回收
//不存在代表被回收了
return !retainedKeys.contains(reference.key);
}
private void removeWeaklyReachableReferences() {
//如果队列中有元素,代表GC是已经将对象给回收掉
//每从队列中去除一个元素,同时在retainedKeys这个集合中移除相应的key值。
KeyedWeakReference ref;
while ((ref = (KeyedWeakReference) queue.poll()) != null) {
retainedKeys.remove(ref.key);
}
}
GcTrigger DEFAULT = new GcTrigger() {
@Override public void runGc() {
// Code taken from AOSP FinalizationTest:
// https://android.googlesource.com/platform/libcore/+/master/support/src/test/java/libcore/
// java/lang/ref/FinalizationTester.java
// System.gc() does not garbage collect every time. Runtime.gc() is
最后附上:我们之前因为秋招收集的二十套一二线互联网公司Android面试真题 (含BAT、小米、华为、美团、滴滴)和我自己整理Android复习笔记(包含Android基础知识点、Android扩展知识点、Android源码解析、设计模式汇总、Gradle知识点、常见算法题汇总)
面试成功其实是必然的,因为我做足了充分的准备工作,包括刷题啊,看一些Android核心的知识点,看一些面试的博客吸取大家面试的一些经验,下面这份PDF是我翻阅了差不多1个月左右一些Android大博主的博客从他们那里取其精华去其糟泊所整理出来的一些Android的核心知识点, 全部都是精华中的精华,我能面试到现在资深开发人员跟我整理的这本Android核心知识点有密不可分的关系,在这里本着共赢的心态分享给各位朋友。
这份PDF囊括了JVM,Java集合,Java多线程并发,Java基础,生命周期,微服务, 进程,Parcelable 接口,IPC,屏幕适配,线程异步,ART,架构,Jetpack,NDK开发,计算机网络基础,类加载器,Android 开源库源码分析,设计模式汇总,Gradle 知识点汇总…
由于篇幅有限,就不做过多的介绍,大家请自行脑补
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门,即可获取!
解析、设计模式汇总、Gradle知识点、常见算法题汇总)
[外链图片转存中…(img-avXdEPU5-1715789287513)]
面试成功其实是必然的,因为我做足了充分的准备工作,包括刷题啊,看一些Android核心的知识点,看一些面试的博客吸取大家面试的一些经验,下面这份PDF是我翻阅了差不多1个月左右一些Android大博主的博客从他们那里取其精华去其糟泊所整理出来的一些Android的核心知识点, 全部都是精华中的精华,我能面试到现在资深开发人员跟我整理的这本Android核心知识点有密不可分的关系,在这里本着共赢的心态分享给各位朋友。
[外链图片转存中…(img-nvo7plR8-1715789287515)]
这份PDF囊括了JVM,Java集合,Java多线程并发,Java基础,生命周期,微服务, 进程,Parcelable 接口,IPC,屏幕适配,线程异步,ART,架构,Jetpack,NDK开发,计算机网络基础,类加载器,Android 开源库源码分析,设计模式汇总,Gradle 知识点汇总…
由于篇幅有限,就不做过多的介绍,大家请自行脑补
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门,即可获取!