Search code examples
androidandroid-serviceandroid-9.0-pie

Android 9: Background Restriction App Setting


I'm working on a music player app and I'm noticing weird behavior on Android 9 devices when a user enables the "Background Restriction" setting (Settings -> Apps -> [App Name] -> Battery -> Background Restriction).

Here's what I'm doing: I start my music player service by calling Service.startService() then set it to foreground via Service.startForeground() while my app is in the foreground.

Here's what I'm seeing when "Background Restriction" is turned on: 1) Service.startForeground() will not posting a notification 2) My foreground service is killed by the OS within a minute of my app going to the background

Here's what I see in the logs: 1) "Service.startForeground() not allowed due to bg restriction" when calling Service.startForeground() 2) "Stopping service due to app idle" when my app is auto-killed by the OS

Here's my question: I thought the whole point of a foreground service is to allow background processing with the user's knowledge (an ongoing notification); is the "Background Restriction" setting really intended to disallow all background activity?

Interesting find: Looking at Google's "Universal Music Player" sample project on GitHub, I noticed that their sample project is not being killed like my app is. After digging I noticed this is because they are binding to their service and never unbinding in Activity.onPause(). According to Google's docs, bound services are not subject to the same background restrictions. Is this really the solution to my problem? Seems a little hacky/fragile.

Thanks in advance for the help!


Solution

  • Here's what I've found:

    • "Background Restriction" (or "Allow Background Activity" on some devices) is intended to stop ALL background activity regardless of whether your service has called setForeground()

    • There is no way around this setting. You cannot programmatically disable it. Your only option is to programmatically check if it's enabled using ActivityManager.isBackgroundRestricted() and display a pop-up informing your users on how to disable this setting

    • Google's Universal Music Player sample project on GitHub happens to work (as of the writing of this answer) only because a service bind is not released when the main Activity is paused. The sample project's service is however killed when the main Activity is garbage collected (typically 30-45 minutes depending on the device).