Android 泄漏金丝雀 - 泄漏空 activity

Android leak canary - leaking empty activity

我收到通知,因为我的活动被泄露了,即使活动都是空的。

这是踪迹:

    ApplicationLeak(className=com.bcx.tracker.ui.login.LoginActivity, leakTrace=
    ┬
    ├─ android.app.Activity
    │    Leaking: UNKNOWN
    │    Anonymous subclass of android.app.IRequestFinishCallback$Stub
    │    GC Root: Global variable in native code
    │    ↓ Activity.this[=12=]
    │                 ~~~~~~
    ╰→ com.bcx.tracker.ui.login.LoginActivity
    ​     Leaking: YES (Activity#mDestroyed is true and ObjectWatcher was watching this)
    ​     key = fc3d8e13-c51c-4ff8-995f-4e0da90f085b
    ​     watchDurationMillis = 7889
    ​     retainedDurationMillis = 2886
    ​     key = b809b94b-fd3c-4d26-bda4-7f175624c3c3
    , retainedHeapByteSize=166095)

我刚刚在build.gradle

中添加了依赖
    debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.0-beta-3'

这里有什么我遗漏的吗?

我经历了 但没有帮助。

我的设备:

一加 7,android10

模拟器,android10

这是 Android Framework in Android 10 中的一个已知漏洞:https://issuetracker.google.com/issues/139738913

如果你在 Android 是 Q 时试图完成你的根 activity,不幸的是这会泄漏你的记忆,正如这个推特 thread 所说

Leak introduced when adding support for Bubbles (as chathead activities). Properly reported but: "We've deferred this issue for consideration in a future release."

This leak is happening because IRequestFinishCallback$Stub is an IPC callback that ends up being held by the activity manager process

如前所述,此问题的解决方法

You can "fix" this leak by overriding Activity.onBackPressed() and calling Activity.finishAfterTransition(); instead of super if the activity is task root and the fragment stack is empty.

这是建议添加的完整代码,还用于检查作为根的部分 activity 和片段堆栈是否为空

override fun onBackPressed() {
    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q &&
        isTaskRoot &&
        supportFragmentManager.primaryNavigationFragment?.childFragmentManager?.backStackEntryCount ?: 0 == 0 &&
        supportFragmentManager.backStackEntryCount == 0
    ) {
        finishAfterTransition()
    } else {
        super.onBackPressed()
    }
}

在小米 A2 上测试 - Android Q(android 一个)

您还可以从 google 问题跟踪器 here

跟踪问题更新