Tuesday, 22 March 2022

Android 12 ForegroundServiceStartNotAllowedException while in Foreground?

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.

logs

crash

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()
                )
            }
        }


from Android 12 ForegroundServiceStartNotAllowedException while in Foreground?

No comments:

Post a Comment