检查或捕获警告未能 post 频道通知

Check or catch warning failed to post notification on channel

我知道为什么在我没有创建频道的情况下会出现此警告,但这不是问题所在 ,我想知道的是如何捕获它或检查代码中是否存在通道以便在发布通知之前处理它。

"Developper warning for package "com.app" failed to post notification on channel "channel1" see log for more details" thanks.

您可以使用 NotificationManager.GetNotificationChannel,它将 return NotificationChannel 的实例(如果存在)或 null(如果不存在)的实例。

快速示例:

using (var notificationManager = NotificationManager.FromContext(ApplicationContext))
{
    var channelName = "SomeChannelName";
    if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
    {
        NotificationChannel channel = notificationManager.GetNotificationChannel(channelName);
        if (channel == null)
        {
            channel = new NotificationChannel(channelName, channelName, NotificationImportance.Low)
            {
                LockscreenVisibility = NotificationVisibility.Public
            };
            channel.SetShowBadge(true);
            notificationManager.CreateNotificationChannel(channel);
        }
    }
    // build your notification
}