Context.startForegroundService() did not then call Service.startForeground()
From Google's docs on Android 8.0 behavior changes:
The system allows apps to call Context.startForegroundService() even while the app is in the background. However, the app must call that service's startForeground() method within five seconds after the service is created.
Solution:Call startForeground()
in onCreate()
for the Service
which you use Context.startForegroundService()
See also: Background Execution Limits for Android 8.0 (Oreo)
I called ContextCompat.startForegroundService(this, intent)
to start the service then
In service onCreate
@Override public void onCreate() { super.onCreate(); if (Build.VERSION.SDK_INT >= 26) { String CHANNEL_ID = "my_channel_01"; NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Channel human readable title", NotificationManager.IMPORTANCE_DEFAULT); ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel); Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle("") .setContentText("").build(); startForeground(1, notification); }}
Why this issue is happening is because Android framework can't guarantee your service get started within 5 second but on the other hand framework does have strict limit on foreground notification must be fired within 5 seconds, without checking if framework had tried to start the service.
This is definitely a framework issue, but not all developers facing this issue are doing their best:
startForeground
a notification must be in bothonCreate
andonStartCommand
, because if your service is already created and somehow your activity is trying to start it again,onCreate
won't be called.notification ID must not be 0 otherwise same crash will happen even it's not same reason.
stopSelf
must not be called beforestartForeground
.
With all above 3 this issue can be reduced a bit but still not a fix, the real fix or let's say workaround is to downgrade your target sdk version to 25.
And note that most likely Android P will still carry this issue because Google refuses to even understand what is going on and does not believe this is their fault, read #36 and #56 for more information