You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Xamarin.Android中以最简方式实现本地通知?

最简方式实现Xamarin本地通知

嘿,我太懂你这种被Xamarin本地通知的细节(比如通知渠道)绕得头大的感觉了!其实咱们完全可以用最精简的方式搞定这个功能,不用去啃一堆复杂文档,下面给你一步步拆解:

第一步:准备工作(跨平台通用)

如果想省事儿,直接安装Plugin.LocalNotification这个NuGet包——它已经帮你封装了90%的平台差异细节,不用自己写太多原生代码。当然,要是你不想依赖第三方包,咱们也可以用官方的Xamarin.Essentials或者手动实现核心逻辑,下面重点讲这两种最实用的方式。

第二步:Android端核心配置(必做!Android 8.0+强制要求)

Android 8.0(API 26)之后,所有通知必须绑定到通知渠道,否则根本不会显示。咱们不用搞花里胡哨的多渠道,只建一个默认渠道就行:
在Android项目的MainActivity的OnCreate方法里添加初始化代码:

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    // 先初始化通知渠道
    CreateDefaultNotificationChannel();
    // 其他初始化代码(比如Forms、Essentials)
    Xamarin.Essentials.Platform.Init(this, savedInstanceState);
    global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
    LoadApplication(new App());
}

private void CreateDefaultNotificationChannel()
{
    if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
    {
        var channelId = "default_notification_channel";
        var channelName = "默认通知渠道";
        var channelDesc = "接收应用所有本地通知";
        
        var channel = new NotificationChannel(channelId, channelName, NotificationImportance.Default)
        {
            Description = channelDesc
        };
        
        var notificationManager = (NotificationManager)GetSystemService(NotificationService);
        notificationManager.CreateNotificationChannel(channel);
    }
}
  • 注意:这个渠道只需要初始化一次,App启动时创建就行。

第三步:发送本地通知的最简代码

方式一:用Xamarin.Essentials(官方推荐,最省心)

Xamarin.Essentials的NotificationManager已经封装了跨平台逻辑,一行核心代码就能发通知:

using Xamarin.Essentials;

public async Task SendSimpleLocalNotification()
{
    var notificationRequest = new NotificationRequest
    {
        Id = 1, // 唯一标识通知,用来取消或更新
        Title = "你有新通知",
        Description = "这是一条测试本地通知",
        // Android端指定刚才创建的渠道ID
        Android = new AndroidNotification
        {
            ChannelId = "default_notification_channel",
            SmallIcon = "icon_notification" // 记得在Android项目的Resources/drawable里放这个透明背景的图标
        },
        // iOS端默认配置就行,也可以自定义声音、Badge
        iOS = new iOSNotification
        {
            Sound = UNNotificationSound.Default
        }
    };

    await NotificationManager.Current.ShowNotificationAsync(notificationRequest);
}
  • Android的小图标必须是透明背景的矢量图,不然通知栏会显示空白,随便找个符合要求的图标放进drawable文件夹即可。

方式二:手动实现(不依赖第三方库)

如果不想用Essentials,也可以直接写原生代码调用,核心逻辑很简单:

Android端手动发送

using Android.App;
using Android.Content;

public void SendNotificationAndroid()
{
    // 点击通知要打开的页面
    var intent = new Intent(this, typeof(MainActivity));
    intent.AddFlags(ActivityFlags.ClearTop);
    var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);

    // 构建通知
    var notificationBuilder = new NotificationCompat.Builder(this, "default_notification_channel")
        .SetSmallIcon(Resource.Drawable.icon_notification)
        .SetContentTitle("你有新通知")
        .SetContentText("这是一条测试本地通知")
        .SetAutoCancel(true) // 点击后自动消失
        .SetContentIntent(pendingIntent);

    // 发送通知
    var notificationManager = (NotificationManager)GetSystemService(NotificationService);
    notificationManager.Notify(1, notificationBuilder.Build());
}

iOS端手动发送

iOS不需要渠道,但必须先请求通知权限:
在AppDelegate的FinishedLaunching里添加权限请求:

using UserNotifications;

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    // 请求本地通知权限
    UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound, (granted, error) =>
    {
        if (granted)
        {
            InvokeOnMainThread(() => UIApplication.SharedApplication.RegisterForRemoteNotifications());
        }
    });
    
    return base.FinishedLaunching(app, options);
}

然后写发送通知的代码:

using UserNotifications;

public void SendNotificationiOS()
{
    var content = new UNMutableNotificationContent();
    content.Title = "你有新通知";
    content.Body = "这是一条测试本地通知";
    content.Sound = UNNotificationSound.Default;

    // 这里设置5秒后触发通知,也可以用其他触发方式(比如指定时间)
    var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(5, false);
    var request = UNNotificationRequest.FromIdentifier("test_notification", content, trigger);

    UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
    {
        if (err != null)
        {
            // 处理发送错误
        }
    });
}

几个关键注意点

  • Android 8.0+必须创建通知渠道,这是硬性要求,不能省略,但咱们只需要一个默认渠道就够了。
  • Android的小图标一定要符合规范,不然通知显示会有问题。
  • iOS必须先请求通知权限,否则通知根本发不出去。

这样下来,不管是用官方Essentials还是手动实现,都是最精简的方案,没有多余的复杂配置,先把核心功能跑起来再说!

内容的提问来源于stack exchange,提问作者user19070477

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 20:37:39