java - 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 设备中。请问有人有解决方案或建议吗?
解决方案
您不需要删除频道,您可以将频道分享给您的普通通知频道。你会崩溃,因为stopForeground
是 binder call through ActivityManagerService
,它是跨进程的,和deleteNotificationChannel
through一样NotificationManagerService
,如果NotificationManagerService
速度快,方法enforceDeletingChannelHasNoFgService
会返回true
,这是从android-11.0.0_r38添加的,你会崩溃。
推荐阅读
- python - 存在 python 2.7 时使用 python 3.8 创建虚拟环境
- react-native - Gradle 同步失败:基础:GRADLE_USER_HOME 未知
- mongodb - 猫鼬 findByIdAndUpdate 嵌套不更新对象
- python - 我应该如何在 Airflow 中创建 DAG 子计划?
- algorithm - 非递归编写的斐波那契算法的空间复杂度是多少?
- c++ - 如何从主窗口访问另一个 Windows ui?
- c# - 无法从根提供程序解析范围服务“Services.Contracts.IHandler`1[Services.ProcessFile]”
- c++ - 如何获取数组中所有可能的单词组合?
- spring - Spring Boot 变量转小写
- java - Android Studio:来自 org.apache.commons.math4.stat.descriptive 的 getStandardDeviation() 方法没有给我 Std 的确切值