Resolving TTS Memory Leak detected with LeakCanary

Viewed 364

This is the description of a memory leak detected by LeakCanary: (it occurs when the Android back button is pressed)

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

This is how tts is initialised in my activity:

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()
            }
        })
    }

This is the onDestroy method:

override fun onDestroy() {
        if (mtts != null) {
            mtts.stop()
            mtts.shutdown()
        }
        super.onDestroy()
    }

Why is there a leak and how can I fix it?

I also get this warning in the logs - I'm not sure how bad it is or if it relates to the leak at all:

W/TextToSpeech: stop failed: not bound to TTS engine
1 Answers

The problem is that TextToSpeech keeps a strong reference the context provided in its constructor, a Connection instance is keeping a strong reference to the TextToSpeech instance (since it's its outer class) and a native reference is keeping a reference to the Connection.

One way to fix this is to have bind the TTS service using an application context instead of the activity context.

In initializeTextToSpeech(), instead of:

    mtts = TextToSpeech(this, TextToSpeech.OnInitListener { status ->

Try this:

    mtts = TextToSpeech(getApplicationContext(), TextToSpeech.OnInitListener { status ->
Related