我在 PopupDialog 中发现内存泄漏,但我不知道为什么。
所以我注释掉了所有被覆盖的方法,但我仍然有漏洞。
Bottom Sheet 对话框
class PopupDialog : BottomSheetDialogFragment() {
// Annotated all methods and variable.
}
Activity
fun showPopupDialog() =
PopupDialog().show(supportFragmentManager, "DialogTag.POPUP_DIALOG")
泄漏金丝雀
最佳答案
如果您点击 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 {}
关于android - BottomSheetDialogFragment内存泄漏(使用leakcanary),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54759425/