While it seems there are a few questions on here regarding Android 12 service restrictions, I have yet to see one specific to this use case.
Background: I am starting a foreground service to handle a very long running background media player (Exoplayer). Due to the setup of the app, I cannot use the built in notification manager from exoplayer. However I am seeing an odd behavior from Crashlytics. I am getting ForegroundServiceStartNotAllowedException While the app is undoubtedly in the foreground. Per the logs, it is easy to see the user is navigating the app within a second of the startForeground call.
I am also listening to
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event)
to ensure the app is in a foreground state.
I am beginning to run out of ideas as to what would cause this. As you can see by the timestamps, less than 1 second had gone by. The app has no use cases where the service could even accidentally be started from the background.
Thanks
Edit:
I am also declaring my service type:
<service
android:name=".service.SoundPlayerService"
android:enabled="true"
android:exported="false"
android:foregroundServiceType="mediaPlayback"
android:stopWithTask="false">
<intent-filter>
<action android:name="android.media.browse.MediaBrowserService" />
</intent-filter>
</service>
if (!audioFocusTakenBackground && Application.instance.isAppInForeground) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
startForeground(
ONGOING_NOTIFICATION_ID,
builder.build(),
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
)
} else {
startForeground(
ONGOING_NOTIFICATION_ID,
builder.build()
)
}
}
Edit: Device State tab suggested by @Arlind
Application.instance.isAppInForeground
Is this variable has right value? Maybe this variable gets wrong value. Could you check?
Never try to play audio using your own Service. Always use the MediaSession API as described here: https://developer.android.com/guide/topics/media-apps/audio-app/building-an-audio-app