In my app I use Foreground Service to show a notification when the app goes in background. I created a Notification Channel in the following way:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = getString(R.string.app_name); int importance = NotificationManager.IMPORTANCE_DEFAULT; NotificationChannel channel = new NotificationChannel(TransactionsUtil.getNotificationChannelId(this), name, importance); channel.setDescription("some description"); NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); } Notification notification = new NotificationCompat.Builder(this, TransactionsUtil.getNotificationChannelId(this)) .setSmallIcon("some icon") .setContentTitle("some content") .setContentText("some content") .setContentIntent(pendingIntent) .setChannelId(TransactionsUtil.getNotificationChannelId(this)) .build(); startForeground(NOTIFICATION_ID, notification);
The I delete the notification channel in this way:
private void terminateService() { stopForeground(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.deleteNotificationChannel(getNotificationChannelId(this)); } stopSelf();}
Recently, I'm having some crashes in my app releated to this; in particular, I have the following error:
Fatal Exception: java.lang.SecurityExceptionNot allowed to delete channel "channel name" with a foreground service
The problem is releated to the function terminateService, in particular in deleteNotificationChannel.
Caused by android.os.RemoteExceptionRemote stack trace: at com.android.server.notification.NotificationManagerService$11.enforceDeletingChannelHasNoFgService(NotificationManagerService.java:3859) at com.android.server.notification.NotificationManagerService$11.deleteNotificationChannel(NotificationManagerService.java:3872) at android.app.INotificationManager$Stub.onTransact(INotificationManager.java:1813) at android.os.Binder.execTransactInternal(Binder.java:1170) at android.os.Binder.execTransact(Binder.java:1134)
It happens only in Android 11 devices. Does someone has a solution or suggestion, please?