I am working on an app that needs to keep reading aloud text after the screen is turned off. To achieve this goal, I put the Text-to-speech (TTS) code in the foreground service, so the TTS can keep running when the screen is off.
It worked well on my phone before. But after I upgraded my phone from Android 11 to Android 12, the TTS stops working after the screen is turned off for a while, usually after several minutes.
Normally, after the TTS finishes speaking one sentence, it will call the onDone
method of the UtteranceProgressListener
, so I can make the TTS speak next sentence there. The reason the TTS stops working is that the onDone
method stops getting called after the screen is turned off for a while. It doesn't stop immediately, but stops after a few minutes, sometimes longer, sometimes shorter.
EDIT:
At the beginning I turn off the battery optimization for the whole system, but it doesn't work. Then I turn off the battery optimization for a single app. I need to go to the settings for a single app and turn it off, or do it programmatically like this:
Check if battery optimization is enabled or not for an app
This issue is greatly improved after I turn off the battery optimization for a single app. However, the TTS still stops once for a while, about once for several hours. I also notice that the app "T2S" can keep running even when its battery optimization is on. What can I do to let TTS keep running when the battery optimization is on, just like what "T2S" does, or at least don't let it stop after battery optimization is off?
This code is working in Android 12 even app is background