18

问题描述

当我尝试NotificationAndroid O中发送 a 时,我必须指定NotificationChannel要发送到的 a。

如果我像这样使用旧方法(不设置任何频道)NotificationCompat.Builder(this)Notification则不会显示。

对于像这样的无效频道也是如此NotificationCompat.Builder(this, "invalid")NotificationCompat.Builder(this, "")

当我通过Firebase Cloud Messaging发送通知并将我的应用程序置于后台且未指定通知通道时,它将是“杂项”通道中的通知。

当我尝试在上面提到的前台执行相同操作时,将无法创建名称为“Miscellaneous”且 ID为“{package}.MISCELLANEOUS”的通知通道,然后通过它发送。当我这样做时,会发生以下情况:

我的应用程序设置的屏幕截图

我想知道的

如何在没有像FCM这样的渠道的情况下发送通知,以便它进入常规的“杂项”渠道?

这个工作的例子

正如我上面提到的,它发生在FCM 通知中,但例如Gmail也使用杂项通道。那么我该如何使用它呢?

Gmail 通知渠道的屏幕截图

我相信如果杂项频道通常无法使用,他们会删除它。

简短的描述

为什么这段代码没有向“杂项”通知通道发送通知,它实际上没有发送任何通知(仅在 Android O 上,该代码适用于较低的 Android 版本)。

(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).notify(1, NotificationCompat.Builder(this, NotificationChannel.DEFAULT_CHANNEL_ID)
                    .setSmallIcon(R.drawable.small_icon)
                    .setContentTitle(URLDecoder.decode("Title", "UTF-8"))
                    .setContentText(URLDecoder.decode("Text", "UTF-8"))
                    .setColor(ContextCompat.getColor(applicationContext, R.color.color))
                    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                    .setContentIntent(PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT))
                    .build())
4

2 回答 2

10

该频道的 ID 是fcm_fallback_notification_channel。firebase-messaging 库在内部创建它。

https://github.com/firebase/firebase-android-sdk/blob/076c26db27dd54d809fb2ccff8593b64fb3db043/firebase-messaging/src/main/java/com/google/firebase/messaging/CommonNotificationBuilder.java#L66

于 2017-08-29T04:06:11.693 回答
5

正如在另一个答案中所说,Android系统创建的默认频道的ID是fcm_fallback_notification_channel,但要小心,因为系统在必须管理第一个推送通知之前不会创建频道。因此,如果您在FirebaseMessagingService类扩展中管理所有通知,则可能会发生通道不存在并且您遇到如下错误:

android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=fcm_fallback_notification_channel pri=-2 contentView=null vibrate=null sound=null defaults=0x0 flags=0x40 color=0x00000000 vis=PRIVATE)

我的建议是在创建通知之前检查默认通道是否存在,如果不存在则创建它:

private void createDefaultNotificationChannel() {
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
     NotificationManager notificationManager = getSystemService(NotificationManager.class);

     if (notificationManager.getNotificationChannel("fcm_fallback_notification_channel") != null) {
       return;
     }

     String channelName = getString(R.string.fcm_fallback_notification_channel_label);
     NotificationChannel channel = new NotificationChannel("fcm_fallback_notification_channel", channelName, NotificationManager.IMPORTANCE_HIGH);
     notificationManager.createNotificationChannel(channel);
}
于 2018-06-04T14:38:06.430 回答