Bound service crash with "Context.startForegroundService() did not then call Service.startForeground()" error
To expand on UdeshUk's answer - any use of MediaButtonReceiver
(either building pending intents or just receiving media button intents) can result in your service being called with startForegroundService
, because MediaButtonReceiver.onReceive
starts your service in that way on Oreo. I haven't seen this documented anywhere.
I found the problem. In my notification I have set
setDeleteIntent(MediaButtonReceiver.buildMediaButtonPendingIntent(service, PlaybackStateCompat.ACTION_STOP))
So when user removes the notification it calls startForegroundService() because I called stopForeground() previously when pausing.
To overcome, I used a custom pending intent and handled it in the onStartCommand()
instead of MediaButtonReveiver's PendingIntent
You must call this method inside your Service class onCreate() method:->
private void startServiceOreoCondition(){
if (Build.VERSION.SDK_INT >= 26) {
String CHANNEL_ID = "my_service";
String CHANNEL_NAME = "My Background Service";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
CHANNEL_NAME,NotificationManager.IMPORTANCE_NONE);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setCategory(Notification.CATEGORY_SERVICE).setSmallIcon(R.drawable.ic_tgc_icon).setPriority(PRIORITY_MIN).build();
startForeground(101, notification);
}
}