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>()

效果
作者:AlexSJC
本文采用 CC BY-NC-ND 4.0 许可协议
暂无评论

发送评论 编辑评论


|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇