LeakCanary使用和工作原理分析

LeakCanary是一个非常受欢迎的android内存泄漏检测工具,只需要在项目中引入即可

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

然后 没有什么 初始化,注册 之类的任何操作,就OK了。
很是奇怪,下面从 LeakCanary 如何启动调用和工作原理做一下 简单的总结分析;

LeakCanary如何启动调用

既然LeakCanary,没有任何初始化的代码调用,LeakCanary 就有可能在AndroidManifest清单文件中 声明了ContentProvider,借助ContentProvider的特性来实现初始化;
先看一下 debug.apk中的 清单文件内容:


image.png

果然如此,LeakCanary的aar中 已经声明了这个 AppWatcherInstaller 对象,所以就不需要在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 内容提供者的代码。
自定义的AppWatcherInstaller 对象,会在Application调用onCreate方法之前,创建并调用其自身的onCraete方法;
而且注释中 已经给出了 这一解释, Content providers are loaded before the application class is created. [AppWatcherInstaller] is used to install [leakcanary.AppWatcher] on application start
从而 调用

AppWatcher.manualInstall(application)

触发了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的初始化 先调用了AppWatcher的manualInstall方法,然后又调用了 InternalAppWatcher的 install方法,关键代码就在 install方法中;
install方法进行了如下操作:

  1. 检测当前是否在主线程

checkMainThread()

  1. 持有Application对象

InternalAppWatcher.application = application

3.分别调了ActivityDestroyWatcher和FragmentDestroyWatcher 的伴生对象的 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 注册了一个 Activity生命周期变化监听的对象 lifecycleCallbacks ;在每个Activity对象 被销毁 调用onDestroyed方法时,使用objectWatcher 对象来 检测activity对象的回收

  • FragmentDestroyWatcher.install
    FragmentDestroyWatcher.install方法,和ActivityDestroyWatcher.install类型,也是为aplication对象 注册了一个Activity生命周期变化的监听对象,但是主要是为了 监听Fragment对象的销毁 ,在调用 onFragmentDestroyed(),onFragmentViewDestroyed()时,使用objectWatcher 对象来 检测view对象和fragment对象的回收。
//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 检测对象是否被回收

LeakCanary 检测内存泄漏的关键就是,在Activity或者Fragment销毁的时候,触发一次gc内存回收,然后判断Activity或者Fragment对象 是否依然存在,如果对象依然存在没有被回收,就说明 可能存在内存泄漏,积累过多可能引发OOM内存溢出。
这样就有一个 疑问,如何判断一个对象是否被gc回收呢?

借助弱引用的特性,只要jvm的垃圾回收器 扫描到 弱引用对象 ,弱引用对象 就会被回收释放掉,但是如果 没有被回收 只能说明 这个对象还被其他static变量引用 或者native method引用;
伪代码如下:

        Integer a=1;
        ReferenceQueue referenceQueue = new ReferenceQueue<>();
        WeakReference weakReference = new WeakReference<>(a, referenceQueue);
        //触发gc,5秒后 检测referenceQueue是否存在对象
        System.gc();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (referenceQueue.poll() != null) {
                    //a对象 已经被回收
                }
            }
        },5000);

你可能感兴趣的:(LeakCanary使用和工作原理分析)