Android开发经验谈Android开发Android技术知识

监测内存泄漏--LeakCanary源码分析

2018-11-07  本文已影响22人  秋阳君

1 在全局Application类中注册:

LeakCanary.install(this);
点进去看源码:

  public static RefWatcher install(Application application) {
    return refWatcher(application)         // 1-1
        .listenerServiceClass(DisplayLeakService.class)  // 1-2
        .excludedRefs(AndroidExcludedRefs.createAppDefaults().build())  //1-3
        .buildAndInstall();   // 1-4 和 2-1
  }

源码分为四部分:

2 RefWatcher 监听内存泄漏(1-4中开始):

2-1RefWatcher将全局的context传入

  public RefWatcher buildAndInstall() {
    RefWatcher refWatcher = build();
    if (refWatcher != DISABLED) {
      LeakCanary.enableDisplayLeakActivity(context);
      ActivityRefWatcher.install((Application) context, refWatcher);   //重点 2-2
    }
    return refWatcher;
  }

2-2创建一个ActivityRefWatcher()对象

 public static void install(Application application, RefWatcher refWatcher) {
    new ActivityRefWatcher(application, refWatcher).watchActivities();
  }

2-3 ActivityRefWather对象中的重点方法 监听Activity的生命周期,在Activity销毁时,调用RefWatcher的方法:

private final Application.ActivityLifecycleCallbacks lifecycleCallbacks =
      new Application.ActivityLifecycleCallbacks() {
        @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        }
​
        @Override public void onActivityStarted(Activity activity) {
        }
​
        @Override public void onActivityResumed(Activity activity) {
        }
​
        @Override public void onActivityPaused(Activity activity) {
        }
​
        @Override public void onActivityStopped(Activity activity) {
        }
​
        @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
        }
​
        @Override public void onActivityDestroyed(Activity activity) {
          ActivityRefWatcher.this.onActivityDestroyed(activity);   //重点调用 2-4
        }
      };

2-4 ActivityRefWatcher.this.onActivityDestroyed(activity) 将Activity添加到监测队列中:

  void onActivityDestroyed(Activity activity) {
    refWatcher.watch(activity);
  }
public void watch(Object watchedReference) {
    watch(watchedReference, "");
  }

3 watch()方法:将Activity封装为弱引用对象,查看是否被回收

public void watch(Object watchedReference, String referenceName) {
    if (this == DISABLED) {
      return;
    }
    checkNotNull(watchedReference, "watchedReference"); 
    checkNotNull(referenceName, "referenceName");
    final long watchStartNanoTime = System.nanoTime();
    String key = UUID.randomUUID().toString();
    retainedKeys.add(key);
    final KeyedWeakReference reference =
        new KeyedWeakReference(watchedReference, key, referenceName, queue);   //重点  3-1
​
    ensureGoneAsync(watchStartNanoTime, reference);// 重点 3-2
  }
  private void ensureGoneAsync(final long watchStartNanoTime, final KeyedWeakReference reference) {
    watchExecutor.execute(new Retryable() {
      @Override public Retryable.Result run() {
        return ensureGone(reference, watchStartNanoTime);  //4-1
      }
    });
  }

4 监测分析的最重点方法 ensureGone()

Retryable.Result ensureGone(final KeyedWeakReference reference, final long watchStartNanoTime) {
    long gcStartNanoTime = System.nanoTime(); 
    long watchDurationMs = NANOSECONDS.toMillis(gcStartNanoTime - watchStartNanoTime); //gc结束的时间
​
    removeWeaklyReachableReferences();  // 4-1
​
    if (debuggerControl.isDebuggerAttached()) {
      // The debugger can create false leaks.
      return RETRY;
    }
    if (gone(reference)) {   // 4-2
      return DONE;
    }
    gcTrigger.runGc();  
    removeWeaklyReachableReferences();
    if (!gone(reference)) {
      long startDumpHeap = System.nanoTime();
      long gcDurationMs = NANOSECONDS.toMillis(startDumpHeap - gcStartNanoTime);
​
      File heapDumpFile = heapDumper.dumpHeap();
      if (heapDumpFile == RETRY_LATER) {
        // Could not dump the heap.
        return RETRY;
      }
      long heapDumpDurationMs = NANOSECONDS.toMillis(System.nanoTime() - startDumpHeap);
      heapdumpListener.analyze(
          new HeapDump(heapDumpFile, reference.key, reference.name, excludedRefs, watchDurationMs,
              gcDurationMs, heapDumpDurationMs));
    }
    return DONE;
  }
private void removeWeaklyReachableReferences() {
    // WeakReferences are enqueued as soon as the object to which they point to becomes weakly
    // reachable. This is before finalization or garbage collection has actually happened.
    KeyedWeakReference ref;
    while ((ref = (KeyedWeakReference) queue.poll()) != null) {
      retainedKeys.remove(ref.key);
    }
  }
  private boolean gone(KeyedWeakReference reference) {
    return !retainedKeys.contains(reference.key);
  }
上一篇 下一篇

猜你喜欢

热点阅读