Search code examples
androidandroid-serviceforeground-service

Service.startForeground() not allowed due to mAllowStartForeground false when triggered from Activity.onStop


After exhaustive investigation based on similar issues, I have to try and get some input on my specific case.

I have an Android application that consists of an activity and a service. When the activity is started, I start the service (as a normal background service) by calling startService(). When the user closes the app (so in Activity.onStop) I move the Service to a foreground service, by calling startForeground with an appropriate notification. Usually this works fine. But I do occasionally get ForegroundServiceStartNotAllowedException with Service.startForeground() not allowed due to mAllowStartForeground false reported.

I cannot reproduce this on locally (either debug or production). From the crash logs, this does not seem to affect all users, and the users that are affected only see this occasionally.

As far as I can gather, I am following the correct steps to handle this, as is evidenced by the fact that it works in most cases.

I have tried builder.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE); and the service is declared as android:foregroundServiceType="location"

My best guess was that in some cases the StartForeground isn't called quickly enough (as I understand the OS gives a short window to do this type of switch), but I cannot confirm this. Also in OnStop, I call this immediately, and the notification is pre-created, so I don't know how this could be sped up?

Any assistance would be greatly appreciated!


Solution

  • Your app is already in the background when this exception is thrown. You'll have to start the foreground Service before your app goes to the background. See Fatal Android 12: Exception: startForegroundService() not allowed due to mAllowStartForeground false and https://developer.android.com/develop/background-work/services/foreground-services#background-start-restrictions

    As a workaround, you might try setting the Service to a foreground Service in onPause() instead of onStop() and return it to a background Service in onResume(). That might be a way to work around this.