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.
Edited:
At the beginning I turned off the battery optimization for the whole system, but it doesn't work. Then I turned off the battery optimization for a specific 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 about once for several hours. I also noticed that the app "T2S" can keep running TTS even when its battery optimization is turned on. What can I do to let TTS keep running when the battery optimization is turned on, just like "T2S" does, or at least never stop after battery optimization is turned off?