我在调试应用程序中使用leakCanary,每次我的片段被销毁时,我都会收到泄漏警告。泄漏树首先表示片段中没有泄漏,只有这部分泄漏,并且泄漏在每个片段上。
这次泄漏意味着什么?有办法避免吗?
androidx.constraintlayout.widget.ConstraintLayout instance
Leaking: YES (ObjectWatcher was watching this because MyFragment received
Fragment#onDestroyView() callback (references to its views should be
cleared to prevent leaks))
Retaining 13.0 kB in 124 objects
key = 0b4d582b-b8ac-42dc-aebf-7b7b0804c92e
watchDurationMillis = 127274
retainedDurationMillis = 122272
View not part of a window view hierarchy
View.mAttachInfo is null (view detached)
View.mWindowAttachCount = 1
mContext instance of via.driver.v2.map.MapActivityV2 with mDestroyed =
false
您应该始终清除对片段
onDestroyView
或 onDestroy
方法上的视图的所有引用,因为如果不这样做,肯定会发生内存泄漏。这看起来像是谷歌地图泄漏,据我所知它一直有这个问题。
尝试使用下面的代码,它应该不会再发生:
@Override
protected void onDestroy() {
super.onDestroy();
mMap.clear();
mapView.onDestroy();
mapView.removeAllViews();
}