android - BottomSheetDialogFragment内存泄漏(使用leakcanary)

标签 android memory-leaks bottom-sheet leakcanary

我在 PopupDialog 中发现内存泄漏,但我不知道为什么。

所以我注释掉了所有被覆盖的方法,但我仍然有漏洞。

Bottom Sheet 对话框

class PopupDialog : BottomSheetDialogFragment() {

    // Annotated all methods and variable.

}

Activity

fun showPopupDialog() = 
    PopupDialog().show(supportFragmentManager, "DialogTag.POPUP_DIALOG")

泄漏金丝雀

enter image description here

最佳答案

如果您点击 Message.obj (excluded) 节点,您将看到以下消息。

Excluded by rule matching field android.os.Message#obj because A thread waiting on a blocking queue will leak the last dequeued object as a stack local reference. So when a HandlerThread becomes idle, it keeps a local reference to the last message it received. That message then gets recycled and can be used again. As long as all messages are recycled after being used, this won't be a problem, because these references are cleared when being recycled. However, dialogs create template Message instances to be copied when a message needs to be sent. These Message templates holds references to the dialog listeners, which most likely leads to holding a reference onto the activity in some way. Dialogs never recycle their template Message, assuming these Message instances will get GCed when the dialog is GCed. The combination of these two things creates a high potential for memory leaks as soon as you use dialogs. These memory leaks might be temporary, but some handler threads sleep for a long time. To fix this, you could post empty messages to the idle handler threads from time to time. This won't be easy because you cannot access all handler threads, but a library that is widely used should consider doing this for its own handler threads. This leaks has been shown to happen in both Dalvik and ART.

如消息中所建议的,您可以发布到附加到主线程循环程序的处理程序。您可以在对话框关闭后执行此操作。

在主线程上创建的处理程序将附加到主线程的循环程序。

所以你可以这样做 existingHander.post {} 或者要创建一个新的处理程序,您可以这样做 Handler(Looper.getMainLooper()).post {}

来源:https://github.com/square/leakcanary/blob/master/leakcanary-android/src/main/java/com/squareup/leakcanary/AndroidExcludedRefs.java#L128

关于android - BottomSheetDialogFragment内存泄漏(使用leakcanary),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54759425/

相关文章:

android - 在 BottomSheet fragment 中选择项目时刷新 Activity

android - Jetpack 撰写 : BottomSheet state change callback

android - OrmLite、日历和时间戳

android - 线性布局中的嵌套权重

祖 parent 上的 JavaFX addEventListener 内存泄漏

supervisord 可以用于程序的内存和 CPU 使用情况分析吗

Android BottomSheetDialogFragment 在圆角后面有颜色

android - 如何在 Android Studio 中为文本添加下划线?

java - 找到 NFC 标签时 Activity 重新打开

java - libGDX - 使用 HashMap 会导致 Android 手机上的 HeapSize 增加和内存不足