AlexSJC
发布于 2024-01-12 / 11 阅读
0
0

Xamarin.Android 更好地管理通知渠道

NotificationHelper

using Android.Content;
using Android.OS;
using System.Reflection;

public static class NotificationHelper
{
    public static void Init<T>()
    {
        if (Build.VERSION.SdkInt < BuildVersionCodes.O)
            return;
        var fields = typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static);
        var groups = fields.Where(f => f.FieldType == typeof(NotificationChannelGroup))
                           .Select(f => f.GetValue(null) as NotificationChannelGroup)
                           .ToList();
        var channels = fields.Where(f => f.FieldType == typeof(NotificationChannel))
                             .Select(f => f.GetValue(null) as NotificationChannel)
                             .ToList();
        var manager = (NotificationManager)Application.Context.GetSystemService(Context.NotificationService);
        foreach (var group in manager.NotificationChannelGroups)
        {
            if (!groups.Any(g => g.Id == group.Id))
                manager.DeleteNotificationChannelGroup(group.Id);
        }
        foreach (var channel in manager.NotificationChannels)
        {
            if (!channels.Any(c => c.Id == channel.Id))
                manager.DeleteNotificationChannel(channel.Id);
        }
        manager.CreateNotificationChannelGroups(groups);
        manager.CreateNotificationChannels(channels);
    }
}

Example

创建 NotificationChannels.cs,添加 NotificationChannelNotificationChannelGroup(可选)字段

public class NotificationChannels
{
    public static readonly NotificationChannelGroup Group1 = new("group_1", "Group 1");

    public static readonly NotificationChannel Channel1 = new("channel_1", "Channel 1", NotificationImportance.High) { Group = Group1.Id };
    public static readonly NotificationChannel Channel2 = new("channel_2", "Channel 2", NotificationImportance.Default) { Group = Group1.Id };
    public static readonly NotificationChannel Channel3 = new("channel_3", "Channel 3", NotificationImportance.Default);
}

在合适的位置(如 Activity.OnCreate 方法)调用 NotificationHelper.Init<NotificationChannels>()

效果图


评论