LeakCanary使用和工作原理分析

LeakCanary是一個(gè)非常受歡迎的android內(nèi)存泄漏檢測(cè)工具,只需要在項(xiàng)目中引入即可

debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.5'

然后 沒有什么 初始化,注冊(cè) 之類的任何操作,就OK了。
很是奇怪,下面從 LeakCanary 如何啟動(dòng)調(diào)用和工作原理做一下 簡(jiǎn)單的總結(jié)分析;

LeakCanary如何啟動(dòng)調(diào)用

既然LeakCanary,沒有任何初始化的代碼調(diào)用,LeakCanary 就有可能在AndroidManifest清單文件中 聲明了ContentProvider,借助ContentProvider的特性來(lái)實(shí)現(xiàn)初始化;
先看一下 debug.apk中的 清單文件內(nèi)容:


image.png

果然如此,LeakCanary的aar中 已經(jīng)聲明了這個(gè) AppWatcherInstaller 對(duì)象,所以就不需要在app中的AndroidManifest中 再次聲明了;

/**
 * Content providers are loaded before the application class is created. [AppWatcherInstaller] is
 * used to install [leakcanary.AppWatcher] on application start.
 */
internal sealed class AppWatcherInstaller : ContentProvider() {

  /**
   * [MainProcess] automatically sets up the LeakCanary code that runs in the main app process.
   */
  internal class MainProcess : AppWatcherInstaller()

  /**
   * When using the `leakcanary-android-process` artifact instead of `leakcanary-android`,
   * [LeakCanaryProcess] automatically sets up the LeakCanary code
   */
  internal class LeakCanaryProcess : AppWatcherInstaller()

  override fun onCreate(): Boolean {
    val application = context!!.applicationContext as Application
    AppWatcher.manualInstall(application)
    return true
  }
...

看一下 自定義的AppWatcherInstaller 內(nèi)容提供者的代碼。
自定義的AppWatcherInstaller 對(duì)象,會(huì)在Application調(diào)用onCreate方法之前,創(chuàng)建并調(diào)用其自身的onCraete方法;
而且注釋中 已經(jīng)給出了 這一解釋, Content providers are loaded before the application class is created. [AppWatcherInstaller] is used to install [leakcanary.AppWatcher] on application start
從而 調(diào)用

AppWatcher.manualInstall(application)

觸發(fā)了LeakCanary 的初始化方法;

LeakCanary的工作原理

LeakCanary的初始化

//AppWatcher
  fun manualInstall(application: Application) {
    InternalAppWatcher.install(application)
  }
#InternalAppWatcher
  fun install(application: Application) {
    checkMainThread()
    if (this::application.isInitialized) {
      return
    }
    InternalAppWatcher.application = application
    if (isDebuggableBuild) {
      SharkLog.logger = DefaultCanaryLog()
    }

    val configProvider = { AppWatcher.config }
    ActivityDestroyWatcher.install(application, objectWatcher, configProvider)
    FragmentDestroyWatcher.install(application, objectWatcher, configProvider)
    onAppWatcherInstalled(application)
  }

LeakCanary的初始化 先調(diào)用了AppWatcher的manualInstall方法,然后又調(diào)用了 InternalAppWatcher的 install方法,關(guān)鍵代碼就在 install方法中;
install方法進(jìn)行了如下操作:

  1. 檢測(cè)當(dāng)前是否在主線程

checkMainThread()

  1. 持有Application對(duì)象

InternalAppWatcher.application = application

3.分別調(diào)了ActivityDestroyWatcher和FragmentDestroyWatcher 的伴生對(duì)象的 install 方法

  • ActivityDestroyWatcher.install
//ActivityDestroyWatcher 
internal class ActivityDestroyWatcher private constructor(
  private val objectWatcher: ObjectWatcher,
  private val configProvider: () -> Config
) {

  private val lifecycleCallbacks =
    object : Application.ActivityLifecycleCallbacks by noOpDelegate() {
      override fun onActivityDestroyed(activity: Activity) {
        if (configProvider().watchActivities) {
          objectWatcher.watch(
              activity, "${activity::class.java.name} received Activity#onDestroy() callback"
          )
        }
      }
    }

  companion object {
    fun install(
      application: Application,
      objectWatcher: ObjectWatcher,
      configProvider: () -> Config
    ) {
      val activityDestroyWatcher =
        ActivityDestroyWatcher(objectWatcher, configProvider)
      application.registerActivityLifecycleCallbacks(activityDestroyWatcher.lifecycleCallbacks)
    }
  }
}

ActivityDestroyWatcher.install方法 為application 注冊(cè)了一個(gè) Activity生命周期變化監(jiān)聽的對(duì)象 lifecycleCallbacks ;在每個(gè)Activity對(duì)象 被銷毀 調(diào)用onDestroyed方法時(shí),使用objectWatcher 對(duì)象來(lái) 檢測(cè)activity對(duì)象的回收

  • FragmentDestroyWatcher.install
    FragmentDestroyWatcher.install方法,和ActivityDestroyWatcher.install類型,也是為aplication對(duì)象 注冊(cè)了一個(gè)Activity生命周期變化的監(jiān)聽對(duì)象,但是主要是為了 監(jiān)聽Fragment對(duì)象的銷毀 ,在調(diào)用 onFragmentDestroyed(),onFragmentViewDestroyed()時(shí),使用objectWatcher 對(duì)象來(lái) 檢測(cè)view對(duì)象和fragment對(duì)象的回收。
//FragmentDestroyWatcher
fun install(
    application: Application,
    objectWatcher: ObjectWatcher,
    configProvider: () -> AppWatcher.Config
  ) {
    val fragmentDestroyWatchers = mutableListOf<(Activity) -> Unit>()

    if (SDK_INT >= O) {
      fragmentDestroyWatchers.add(
          AndroidOFragmentDestroyWatcher(objectWatcher, configProvider)
      )
    }
    ...
    application.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks by noOpDelegate() {
      override fun onActivityCreated(
        activity: Activity,
        savedInstanceState: Bundle?
      ) {
        for (watcher in fragmentDestroyWatchers) {
          watcher(activity)
        }
      }
    })
  }
//AndroidOFragmentDestroyWatcher
internal class AndroidOFragmentDestroyWatcher(
  private val objectWatcher: ObjectWatcher,
  private val configProvider: () -> Config
) : (Activity) -> Unit {
  private val fragmentLifecycleCallbacks = object : FragmentManager.FragmentLifecycleCallbacks() {

    override fun onFragmentViewDestroyed(
      fm: FragmentManager,
      fragment: Fragment
    ) {
      val view = fragment.view
      if (view != null && configProvider().watchFragmentViews) {
        objectWatcher.watch(
            view, "${fragment::class.java.name} received Fragment#onDestroyView() callback " +
            "(references to its views should be cleared to prevent leaks)"
        )
      }
    }

    override fun onFragmentDestroyed(
      fm: FragmentManager,
      fragment: Fragment
    ) {
      if (configProvider().watchFragments) {
        objectWatcher.watch(
            fragment, "${fragment::class.java.name} received Fragment#onDestroy() callback"
        )
      }
    }
  }

  override fun invoke(activity: Activity) {
    val fragmentManager = activity.fragmentManager
    fragmentManager.registerFragmentLifecycleCallbacks(fragmentLifecycleCallbacks, true)
  }
}

LeakCanary 檢測(cè)對(duì)象是否被回收

LeakCanary 檢測(cè)內(nèi)存泄漏的關(guān)鍵就是,在Activity或者Fragment銷毀的時(shí)候,觸發(fā)一次gc內(nèi)存回收,然后判斷Activity或者Fragment對(duì)象 是否依然存在,如果對(duì)象依然存在沒有被回收,就說(shuō)明 可能存在內(nèi)存泄漏,積累過(guò)多可能引發(fā)OOM內(nèi)存溢出。
這樣就有一個(gè) 疑問(wèn),如何判斷一個(gè)對(duì)象是否被gc回收呢?

借助弱引用的特性,只要jvm的垃圾回收器 掃描到 弱引用對(duì)象 ,弱引用對(duì)象 就會(huì)被回收釋放掉,但是如果 沒有被回收 只能說(shuō)明 這個(gè)對(duì)象還被其他static變量引用 或者native method引用;
偽代碼如下:

        Integer a=1;
        ReferenceQueue<Integer> referenceQueue = new ReferenceQueue<>();
        WeakReference<Integer> weakReference = new WeakReference<>(a, referenceQueue);
        //觸發(fā)gc,5秒后 檢測(cè)referenceQueue是否存在對(duì)象
        System.gc();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (referenceQueue.poll() != null) {
                    //a對(duì)象 已經(jīng)被回收
                }
            }
        },5000);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容