首页 > 解决方案 > Android 11 中的 deleteNotificationChannel 崩溃

问题描述

在我的应用程序中,我使用前台服务在应用程序进入后台时显示通知。我通过以下方式创建了一个通知通道:

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);

我以这种方式删除通知通道:

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();
}

最近,我的应用程序出现了一些与此相关的崩溃;特别是,我有以下错误:

致命异常:java.lang.SecurityException 不允许使用前台服务删除通道“通道名称”

该问题与函数 terminateService 有关,特别是在 deleteNotificationChannel 中。

由 android.os.RemoteException 引起远程堆栈跟踪:在 com.android.server.notification.NotificationManagerService$11.enforceDeletingChannelHasNoFgService(NotificationManagerService.java:3859) 在 com.android.server.notification.NotificationManagerService$11.deleteNotificationChannel(NotificationManagerService.java:3872 ) 在 android.os.Binder.execTransactInternal(Binder.java:1170) 在 android.os.Binder.execTransact(Binder.java:1134) 的 android.app.INotificationManager$Stub.onTransact(INotificationManager.java:1813)

它仅发生在 Android 11 设备中。请问有人有解决方案或建议吗?

标签: javaandroidcrashforeground-serviceandroid-11

解决方案


您不需要删除频道,您可以将频道分享给您的普通通知频道。你会崩溃,因为stopForeground是 binder call through ActivityManagerService,它是跨进程的,和deleteNotificationChannelthrough一样NotificationManagerService,如果NotificationManagerService速度快,方法enforceDeletingChannelHasNoFgService会返回true,这是从android-11.0.0_r38添加的,你会崩溃。


推荐阅读