我对内存泄漏以及导致内存泄漏的原因有基本的了解.这就是为什么我不明白我的代码中是否有问题,或者是误报.我不知道该分享哪部分代码,因为这个项目并不小.但是请在 comments 中告诉我,我会添加所需的代码.
I use navigation arch component and follow MVVM pattern. I added LeakCanary library later in the development of project and it immediately started to give me warnings about retained instances when I navigate between screens.
The problem occurs when I add fragments to the back stack. With each added fragment to the back stack the counter of retained instances increases. When it reaches the threshold value of 5 LeakCanary dumps the heap and provides report.
But if I click on back button and return to previous screens then counter of retained instances decreases and eventually, when returned to 1st screen all retained instances disappear.
If I look at heap analysis reports it says that the variable coordinatorLayout which is a reference to the CoordinatorLayout
in xml has leaked. If I remove the variable and all of its usage and run the app again I see the same problem, but now with another variable that is a reference to another view in xml. I tried to remove all of the views and their usage that LeakCanary reported as leaking. When it said that a TextView
, which is just used to set a text in onViewCreated
and not used anywhere else, is leaking I started to doubt that there is a problem in my code.
我分析了片段中的生命周期方法调用,注意到当我导航到前一个片段的新屏幕时,调用了onDestroyView
及之前的所有方法,但不调用onDestroy
.当我单击"上一步"时,会为位于后台堆栈顶部的片段调用onDestroy
,并且保留的实例计数器会减少.
我怀疑导航组件将片段的实例保留在后台堆栈中,而LeakCanary将其视为泄漏.