如何设置应用在后台时收到的通知消息的默认通知渠道?这些消息默认使用“杂项”通道。
如您可以在官方文档中看到的,您需要在应用程序组件内的AndroidManifest.xml
中添加以下元数据元素:
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/default_notification_channel_id"/>
当通知消息没有指定通道或提供的通道尚未被应用程序创建时,将使用此默认通道。
您需要使用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);
}
这个通道应该是唯一的,例如com.mycompany.myapp.urgent
然后在AndroidManifest.xml文件中的application标签中添加对字符串的引用。
<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>
<?xml version="1.0" encoding="UTF-8" ?>
<resources>
<string name="default_notification_channel_id">com.mycompany.myapp.urgent</string>
</resources>
<widget
...
xmlns:android="http://schemas.android.com/apk/res/android"
...>
<platform name="android">
<config-file target="AndroidManifest.xml" parent="application" mode="merge">
<meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="@string/default_notification_channel_id"/>
</config-file>
<config-file target="res/values/strings.xml" parent="/*">
<string name="default_notification_channel_id">urgent_alert</string>
</config-file>
</platform>
<string name="default_notification_channel_id" translatable="false">fcm_default_channel</string>
然后我发现当时运行的设备处于夜间/暗模式,所以我需要将values/string.xml
复制到values-night/string.xml
(如果不存在则创建一个),这样本地通知就会显示出来。
<string name=“default_notification_channel_id”>Channel ID</string>
,您可以查看此帖子获取更多信息:https://medium.com/exploring-android/exploring-android-o-notification-channels-94cd274f604c。 - chorngestrings.xml
文件,请确保使用xml version
和resources
标签正确格式化它,否则将会出现构建错误。参见:https://developer.android.com/guide/topics/resources/string-resource - Sludge