Firebase:如何在Android应用中设置默认通知频道?

Mak*_*dov 21 android firebase firebase-cloud-messaging android-8.0-oreo

如何为应用程序在后台时出现的通知消息设置默认通知通道?默认情况下,这些消息使用"杂项"通道.

Mak*_*dov 30

正如您在官方文档中所看到的,您需要AndroidManifest.xml在应用程序组件中添加以下元数据元素:

<meta-data
    android:name="com.google.firebase.messaging.default_notification_channel_id"
    android:value="@string/default_notification_channel_id"/>
Run Code Online (Sandbox Code Playgroud)

当通知消息没有指定频道,或者应用程序尚未创建提供的频道时,将使用此默认频道.

  • 当然,在字符串 res 中定义的字符串“Channel ID”必须与 SOMETHING SOMEWHERE 相关吗? (10认同)
  • 这是**default_notification_channel_id** (6认同)
  • 在您的strings.xml文件中,输入`<string name ="default_notification_channel_id">通道ID </ string>`,您可以查看这篇文章了解更多信息:https://medium.com/exploring-android/exploring -Android邻通知通道-94cd274f604c (5认同)
  • 如果我们甚至没有在应用清单中创建像上面这样的默认通知渠道,会发生什么? (4认同)
  • 如果创建“strings.xml”文件,请确保使用“xml version”和“resources”标签正确格式化它,否则您将收到构建错误。请参阅此处:https://developer.android.com/guide/topics/resources/string-resource (3认同)
  • @user1261913我认为没有必要设置自己的默认通知渠道。文档指出:“FCM 提供了带有基本设置的默认通知通道。**如果您喜欢**创建和使用自己的默认通道,请将 default_notification_channel_id 设置为通知通道对象的 ID,如图所示;” (2认同)
  • 在 `&lt;string name=` 之后,确保使用普通引号 `"` 而不是弯曲引号 `“`/`”` (2认同)

Jam*_*ate 5

您需要使用 注册频道NotificationManager CreateNotificationChannel

此示例在 Xamarin 中使用 c#,但广泛适用于其他地方

private void ConfigureNotificationChannel()
{
    if (Build.VERSION.SdkInt < BuildVersionCodes.O)
    {
        // Notification channels are new in API 26 (and not a part of the
        // support library). There is no need to create a notification
        // channel on older versions of Android.
        return;
    }

    var channelId = Resources.GetString(Resource.String.default_notification_channel_id);
    var channelName = "Urgent";
    var importance = NotificationImportance.High;

    //This is the default channel and also appears in the manifest
    var chan = new NotificationChannel(channelId, channelName, importance);

    chan.EnableVibration(true);
    chan.LockscreenVisibility = NotificationVisibility.Public;

    var notificationManager = (NotificationManager)GetSystemService(NotificationService);
    notificationManager.CreateNotificationChannel(chan);

}
Run Code Online (Sandbox Code Playgroud)

该渠道应该是唯一的,例如com.mycompany.myapp.urgent

然后,您可以在AndroidManifest.xml的应用程序标记内添加对字符串的引用

<application android:label="MyApp" android:icon="@mipmap/icon">
    <meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="@string/default_notification_channel_id" />
</application>
Run Code Online (Sandbox Code Playgroud)

最后,在strings.xml中设置字符串

<?xml version="1.0" encoding="UTF-8" ?>
<resources>
    <string name="default_notification_channel_id">com.mycompany.myapp.urgent</string>
</resources>
Run Code Online (Sandbox Code Playgroud)