Home » Android » android – How to keep playback active after the screen is turned off

android – How to keep playback active after the screen is turned off

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have an app with audio playback, but on some devices (mainly Huawei, Samsung, Sony) playback is stopped when the screen goes off.
Note: playback does not stop for some other apps like Spotify, Play Music

I found this answer (for Huawei devices) which suggest to ask user to enable “run in background” permission in battery optimization settings (Battery Manager > Protected Apps) but I would like to avoid asking users to enable it.

Is there some API to enable it programmatically for Huawei, Samsung, Sony or other manufacturers?

Is it possible to detect if app do not have such permission?

EDIT: playback runs in foreground service and app holds wakelock

EDIT 2: I’ve contacted Huawei support related to this issue. I will share more info once resolved.

How to&Answers:

Use a service with foreground priority the newer Android OS versions have a doze function to save battery.

If you already use the service in foreground probably there is something wrong with the way you use the service in your code (give more details).

Here a tutorial about Playing music in the background that could help you.