Reputation: 11
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.SecurityException Not 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.RemoteException Remote 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?
Upvotes: 0
Views: 1445
Reputation: 14628
You don't need to delete the channel, you can share the channel with your normal notification channel.
You get crash because stopForeground
is binder call through ActivityManagerService
, it cross process, same as the deleteNotificationChannel
through NotificationManagerService
, if the NotificationManagerService
goes fast, the method enforceDeletingChannelHasNoFgService
will return true
, which is added from android-11.0.0_r38, and you will get a crash.
Upvotes: 2