当前位置:主页 > android教程 > Android LeakCanary

Android LeakCanary的使用方法介绍

发布:2023-03-06 18:00:02 59


给网友们整理相关的编程文章,网友慎妙竹根据主题投稿了本篇教程内容,涉及到Android、LeakCanary原理、Android、LeakCanary使用、Android LeakCanary相关内容,已被561网友关注,涉猎到的知识点内容可以在下方电子书获得。

Android LeakCanary

1.LeakCanary 如何自动初始化

LeakCanary只需添加依赖就可以实现自动初始化。LeakCanary是通过ContentProvider实现初始化的,在ContentProvider 的 onCreate方法中初始化LeakCanary。并且MainProcessAppWatcherInstaller是在主线程中初始化的。注意:ContentProvider的初始化是在Application的onCreate之前完成的,所以LeakCanary的初始化方法AppWatcher.manualInstall(application)也是在Application的onCreate之前完成的。

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

2.LeakCanary如何检测内存泄漏

2.1LeakCanary初始化时做了什么

AppWatcher.kt

@JvmOverloads
fun manualInstall(
  application: Application,
  retainedDelayMillis: Long = TimeUnit.SECONDS.toMillis(5),
  watchersToInstall: List = appDefaultWatchers(application)
) {
  checkMainThread()
  if (isInstalled) {
    throw IllegalStateException(
      "AppWatcher already installed, see exception cause for prior install call", installCause
    )
  }
  check(retainedDelayMillis >= 0) {
    "retainedDelayMillis $retainedDelayMillis must be at least 0 ms"
  }
  installCause = RuntimeException("manualInstall() first called here")
  this.retainedDelayMillis = retainedDelayMillis
  if (application.isDebuggableBuild) {
    LogcatSharkLog.install()
  }
  // Requires AppWatcher.objectWatcher to be set
  LeakCanaryDelegate.loadLeakCanary(application)
  watchersToInstall.forEach {
    it.install()
  }
}
fun appDefaultWatchers(
  application: Application,
  reachabilityWatcher: ReachabilityWatcher = objectWatcher
): List {
  return listOf(
    ActivityWatcher(application, reachabilityWatcher),
    FragmentAndViewModelWatcher(application, reachabilityWatcher),
    RootViewWatcher(reachabilityWatcher),
    ServiceWatcher(reachabilityWatcher)
  )
}

在appDefaultWatchers方法中,会默认初始化一些Watcher,在默认情况下,我们只会监控Activity,Fragment,RootView,Service这些对象是否泄漏。

2.2LeakCanary如何触发检测

以ActivityWatcher为例:

/**
 * Expects activities to become weakly reachable soon after they receive the [Activity.onDestroy]
 * callback.
 */
class ActivityWatcher(
  private val application: Application,
  private val reachabilityWatcher: ReachabilityWatcher
) : InstallableWatcher {
  private val lifecycleCallbacks =
    object : Application.ActivityLifecycleCallbacks by noOpDelegate() {
      override fun onActivityDestroyed(activity: Activity) {
        reachabilityWatcher.expectWeaklyReachable(
          activity, "${activity::class.java.name} received Activity#onDestroy() callback"
        )
      }
    }
  override fun install() {
    application.registerActivityLifecycleCallbacks(lifecycleCallbacks)
  }
  override fun uninstall() {
    application.unregisterActivityLifecycleCallbacks(lifecycleCallbacks)
  }
}

在Activity.onDestory时,就会触发检测内存泄漏。通过ActivityLifecycleCallbacks监听生命周期变化,在onActivityDestroyed方法中调用ReachabilityWatcher的expectWeaklyReachable方法。

2.3LeakCanary如何检测泄漏的对象

以Activity为例,通过ReachabilityWatcher的expectWeaklyReachable方法检测。

fun interface ReachabilityWatcher {
  /**
   * Expects the provided [watchedObject] to become weakly reachable soon. If not,
   * [watchedObject] will be considered retained.
   */
  fun expectWeaklyReachable(
    watchedObject: Any,
    description: String
  )
}

ObjectWatcher.kt

ObjectWatcher实现ReachabilityWatcher接口。

private val watchedObjects = mutableMapOf()

private val queue = ReferenceQueue()

@Synchronized override fun expectWeaklyReachable(
  watchedObject: Any,
  description: String
) {
  if (!isEnabled()) {
    return
  }
  removeWeaklyReachableObjects()
  val key = UUID.randomUUID()
    .toString()
  val watchUptimeMillis = clock.uptimeMillis()
  val reference =
    KeyedWeakReference(watchedObject, key, description, watchUptimeMillis, queue)
  SharkLog.d {
    "Watching " +
      (if (watchedObject is Class<*>) watchedObject.toString() else "instance of ${watchedObject.javaClass.name}") +
      (if (description.isNotEmpty()) " ($description)" else "") +
      " with key $key"
  }
  watchedObjects[key] = reference
  checkRetainedExecutor.execute {
    moveToRetained(key)
  }
}

1.通过观察的实例watchedObject构建弱引用KeyedWeakReference实例,watchedObject与ReferenceQueue关联,当对象被回收时,该弱引用对象将被存入ReferenceQueue当中。

2.弱引用KeyedWeakReference实例会被被存储在watchedObjects中(Map)。

3.检测过程中,会调用removeWeaklyReachableObjects,将已回收对象从watchedObjects中移除。

4.如果watchedObjects中没有移除对象,证明它没有被回收,那么就会调用moveToRetained。

private fun removeWeaklyReachableObjects() {
  // 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.
  var ref: KeyedWeakReference?
  do {
    ref = queue.poll() as KeyedWeakReference?
    if (ref != null) {
      watchedObjects.remove(ref.key)
    }
  } while (ref != null)
}
@Synchronized private fun moveToRetained(key: String) {
  removeWeaklyReachableObjects()
  val retainedRef = watchedObjects[key]
  if (retainedRef != null) {
    retainedRef.retainedUptimeMillis = clock.uptimeMillis()
    onObjectRetainedListeners.forEach { it.onObjectRetained() }
  }
}

2.4弱引用 WeakReference

只要 GC 发现一个对象只有弱引用,则就会回收此弱引用对象。

public class WeakReference extends Reference {
    public WeakReference(T referent) {
        super(referent);
    }
    public WeakReference(T referent, ReferenceQueue q) {
        super(referent, q);
    }
}
var str: Any? = Any()
val quque = ReferenceQueue()
val weakReference = WeakReference(str, quque)
val weakReference_before_gc = weakReference.get()
Log.v("reference_tag", weakReference_before_gc.toString())
str = null
System.gc()
Handler().postDelayed( {
    val weakReference_after_gc = weakReference.get()
    Log.v("reference_tag", weakReference_after_gc.toString())
}, 2000)

2022-02-27 17:43:04.181 16634-16634/com.example.myapplication V/reference_tag: java.lang.Object@c87946a
2022-02-27 17:43:06.182 16634-16634/com.example.myapplication V/reference_tag: null

到此这篇关于Android LeakCanary的使用方法介绍的文章就介绍到这了,更多相关Android LeakCanary内容请搜索码农之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持码农之家!


参考资料

相关文章

  • Android三方依赖冲突Gradle中exclude的使用

    发布:2023-03-06

    这篇文章主要介绍了Android三方依赖冲突Gradle中exclude的使用,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下


  • Android Flutter实现精灵图的使用详解

    发布:2023-03-03

    在游戏开发中,精灵图会将一个人物所有动作放置在一张图片中,通过坐标定位选取其中一张图展示。本文就来教你如何使用精灵图,感兴趣的可以了解一下


  • Android事件分发机制示例分析

    发布:2023-03-03

    在说事件分发之前,我们先想一个问题,在APP中我们点击一个View的时候,事件是如何传递到这个View的呢?其实这就是我理解的事件分发机制。即当手指点击屏幕时,事件传递到具体View的过程


  • Android开发之PopupWindow实现弹窗效果

    发布:2023-03-10

    这篇文章主要为大家详细介绍了Android开发之PopupWindow实现弹窗效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下


  • Android autojs随时翻译剪贴板单词实现示例

    发布:2023-03-05

    这篇文章主要为大家介绍了Android autojs随时翻译剪贴板单词,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪


  • Android Flutter实现自定义下拉刷新组件

    发布:2023-03-02

    在Flutter开发中官方提供了多平台的下拉刷新组件供开发者使用。本文将改造一下这些组件,实现自定义的下拉刷新组件,感兴趣的可以了解一下


  • Android PickerView底部选择框实现流程详解

    发布:2023-03-12

    本次主要介绍Android中底部弹出框的使用,使用两个案例来说明,首先是时间选择器,然后是自定义底部弹出框的选择器,以下来一一说明他们的使用方法


  • Android Activity共享元素动画示例解析

    发布:2023-03-12

    这篇文章主要为大家介绍了Android Activity共享元素动画示例解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪


网友讨论