这是LeakCanary检测到的内存泄漏描述:(发生在按下Android返回按钮时)
这是我在活动中初始化 tts 的方法:
1 APPLICATION LEAKS
References underlined with "~~~" are likely causes.
Learn more at https://squ.re/leaks.
356182 bytes retained by leaking objects
Displaying only 1 leak trace out of 2 with the same signature
Signature: 2276fec44ae233e0d5bb5b82648d5836c07e3b33
┬───
│ GC Root: Global variable in native code
│
├─ android.speech.tts.TextToSpeech$Connection$1 instance
│ Leaking: UNKNOWN
│ Anonymous subclass of android.speech.tts.ITextToSpeechCallback$Stub
│ ↓ TextToSpeech$Connection$1.this$1
│ ~~~~~~
├─ android.speech.tts.TextToSpeech$Connection instance
│ Leaking: UNKNOWN
│ ↓ TextToSpeech$Connection.this$0
│ ~~~~~~
├─ android.speech.tts.TextToSpeech instance
│ Leaking: UNKNOWN
│ ↓ TextToSpeech.mContext
│ ~~~~~~~~
╰→ com.example.price.SignUpDisplay instance
Leaking: YES (ObjectWatcher was watching this because com.example.price.SignUpDisplay received Activity#onDestroy() callback and Activity#mDestroyed is true)
key = 6965e004-28de-464b-87d7-2668461623e7
watchDurationMillis = 30282
retainedDurationMillis = 25282
这是我在活动中初始化 tts 的方法:
protected fun initializeTextToSpeech() {
mtts = TextToSpeech(this, TextToSpeech.OnInitListener { status ->
// If a success, set the language
if (status == TextToSpeech.SUCCESS) {
res = mtts.setLanguage(Locale.UK)
} else {
Toast.makeText(
this,
"Feature not supported in your device", Toast.LENGTH_SHORT
).show()
}
})
}
这是 onDestroy 方法:
override fun onDestroy() {
if (mtts != null) {
mtts.stop()
mtts.shutdown()
}
super.onDestroy()
}
为什么会发生泄漏,我该如何修复?
日志中也出现了这个警告 - 我不确定它有多严重或是否与泄漏有关:
W/TextToSpeech: stop failed: not bound to TTS engine