【问题标题】:Leak canary detects some memory leak on detach fragmentsLeak Canary 在分离片段上检测到一些内存泄漏
【发布时间】:2019-10-27 21:37:05
【问题描述】:

当我从活动中分离片段时,Leak Canary 会检测到 androidx.core.widget.NestedScrollView 内部的一些内存泄漏。我没有可观察的,只有一个绑定到其数据绑定对象的视图模型。

ApplicationLeak(className=androidx.core.widget.NestedScrollView, leakTrace=
┬
.
.
.
│    ↓ MainActivity.controller
├─ com.ncapdevi.fragnav.FragNavController
│    Leaking: NO (ArrayList↓ is not leaking)
│    ↓ FragNavController.rootFragments
├─ java.util.ArrayList
│    Leaking: NO (Object[]↓ is not leaking)
│    ↓ ArrayList.elementData
├─ java.lang.Object[]
│    Leaking: NO (MoreFragment↓ is not leaking)
│    ↓ array Object[].[3]
├─ my.package.name.ui.main.more.MoreFragment
│    Leaking: NO (Fragment#mFragmentManager is not null)
│    Fragment.mTag=my.package.name.ui.main.more.MoreFragment4
│    ↓ MoreFragment.binding
│                   ~~~~~~~
├─ my.package.name.databinding.FragmentMoreBindingImpl
│    Leaking: UNKNOWN
│    ↓ FragmentMoreBindingImpl.mRoot
│                              ~~~~~
╰→ androidx.core.widget.NestedScrollView
      Leaking: YES (ObjectWatcher was watching this)
      mContext instance of my.package.name.ui.main.MainActivity with mDestroyed = false
      View#mParent is null
      View#mAttachInfo is null (view detached)
      View.mWindowAttachCount = 1
      key = 2262922d-06f8-4abb-ba7b-d276c6fe3082
      watchDurationMillis = 1910
      retainedDurationMillis = -1
, retainedHeapByteSize=7132)

【问题讨论】:

    标签: memory-leaks android-architecture-components android-viewmodel leakcanary


    【解决方案1】:

    MoreFragment 在 onDestroyView 之后持有 FragmentMoreBindingImpl(它本身持有 NestedScrollView)。您应该清除 Fragment.onDestroyView() 中对绑定的引用

    【讨论】:

    • 我该怎么做?我调用了 binding.unbind() (例如删除其他片段中的所有可观察对象),但存在内存泄漏。
    • unbind() 的 javadoc 说:“删除绑定侦听器到表达式变量”所以不是这样。尝试设置 MoreFragment.binding = null
    • 因为 Koltin,绑定不是空对象,我将其更改为可空对象,一个问题就消失了。我的适配器有另一个问题,它是由 dagger 注入的,并且引用了回收器视图。我修复了它,现在所有问题都修复了:D 谢谢。
    • 很高兴听到!如果这解决了您的问题,您可以将其标记为 ;-)
    猜你喜欢
    • 2019-03-13
    • 2020-08-29
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2012-07-16
    • 1970-01-01
    • 2012-01-22
    相关资源
    最近更新 更多