ForegroundServiceStartNotAllowedException for a Media Player - how are we supposed to handle Foreground Service and AudioFocus in Android 12?

Viewed 240

In Android 12 I play music using MediaPlayer and MediaBrowserServiceCompat.

  1. Playback is ongoing, Service is in Foreground
  2. Taking a call, Service looses AudioFocus so it pauses and exits Foreground
  3. Ending call, Service re-gains AudioFocus, so it resumes playback and enters Foreground again

At this point I am getting the exception:

android.app.ForegroundServiceStartNotAllowedException: Service.startForeground() not allowed due to mAllowStartForeground false: service com.music.player/PlayerService

Sure, but the behaviour described is just what the Media App documentation says to do. So following their rules, results in a crash if I compile for API 31 and run on Android 12.

So how are we supposed to implement this flow on Android 12 then?

1 Answers

My solution was to not stopForeground() in AudioManager.AUDIOFOCUS_LOSS_TRANSIENT. We may gain audio focus again and need to start playing, so don't drop foreground status here.

Related