我正在尝试解决内存泄漏的问题。我有一个CustomActivity
,它添加了一个包含com.example.CustomViewGroup
的Fragment
,后者引用了一个com.example.CustomView
。
class CustomFragment : Fragment() {
override fun onViewCreated(view:View, savedInstanceState:Bundle?)
{
view.findViewById<CustomViewGroup>(R.id.custom_view_group).also { vg ->
lifecycleScope.launch {
...
lifecycleScope.launch {
vg.doSomethingInASuspendMethod()
}
}
}
}
}
class CustomViewGroup : ConstraintLayout {
internal var customView: CustomView? = null
init {
View.inflate(context, R.layout.custom_view_group, this)
customView = findViewById(R.id.custom_view)
...
}
//I've tried numerous things below, but none of them seem to help
override fun onDestroy(owner: LifecycleOwner) {
super.onDestroy(owner)
customView?.onDestroy(owner)
super.onDetachedFromWindow()
customView = null
removeAllViews()
}
}
我已经尝试了onDestroy
中的各种方法,但似乎都没有帮助。我认为这与嵌套协程作用域有关。
58913 bytes retained by leaking objects
Displaying only 1 leak trace out of 2 with the same signature
┬───
│ GC Root: Java local variable
│
├─ kotlinx.coroutines.scheduling.CoroutineScheduler$Worker thread
│ Leaking: UNKNOWN
│ Thread name: 'DefaultDispatcher-worker-1'
│ ↓ CoroutineScheduler$Worker.<Java Local>
│ ~~~~~~~~~~~~
├─ com.example.CustomView instance
│ Leaking: YES (View.mContext references a destroyed activity)
│ mContext instance of com.example.CustomActivity with mDestroyed = true
│ View#mParent is set
│ View#mAttachInfo is null (view detached)
│ View.mID = R.id.null
│ View.mWindowAttachCount = 1
│ ↓ CustomView.mContext
╰→ com.example.CustomActivity instance
Leaking: YES (ObjectWatcher was watching this because com.example.CustomActivity received Activity#onDestroy() callback and Activity#mDestroyed is true)