Not allowed to delete channel MyNotificationChannel with a foreground service - Android 10 and 11 java.lang.SecurityException

1.3k Views Asked by At

I created notification channel when background service is running

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(channelId,
                    "Channel for  notification",
                    NotificationManager.IMPORTANCE_NONE);
        mNotificationManager.createNotificationChannel(channel);
}

In onDestroy function I remove the notification by calling below method by passing the same channel name:

 notificationManager.deleteNotificationChannel(channelId); 

  

When i try to delete that notification on some Devices running Android 10 and 11 got the SecurityException

1

There are 1 best solutions below

1
evoships On

The First step is to neatly catch this exception using a try catch surround when you are trying to delete the channel. The idea is not to delete the channel when we have a foreground service running . So either the service should be stopped or we should not try to delete the channel