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

Xamarin.Forms+Plugin.LocalNotification模拟器本地通知不显示问题排查

问题排查与解决方案

你的代码没弹出通知,核心原因是缺少平台初始化配置和权限申请,另外代码中的catch块也未完成,以下是具体问题和修复步骤:

1. 补全异常捕获逻辑

当前catch块无任何处理代码,甚至缺少闭合语法,先补全以确保能捕获并查看异常细节:

async void Button_Clicked(System.Object sender, System.EventArgs e)
{
    try
    {
        var notification = new NotificationRequest
        {
            NotificationId = 100,
            Title = "Test",
            Description = "Test Description",
            ReturningData = "Dummy data",
            Schedule =
            {
                NotifyTime = DateTime.Now.AddSeconds(5)
            }
        };
        await Plugin.LocalNotification.LocalNotificationCenter.Current.Show(notification);
    }
    catch(Exception ex)
    {
        // 输出异常日志,方便排查问题
        Console.WriteLine($"通知错误:{ex.Message}\n{ex.StackTrace}");
    }
}

2. Android平台强制配置

Android 8.0(API 26)及以上版本要求必须使用通知通道,Plugin.LocalNotification 10.x需在MainApplication中初始化通道:
打开Android项目的MainApplication.cs,在OnCreate方法中添加代码:

using Plugin.LocalNotification;

public class MainApplication : Application
{
    public MainApplication(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer)
    {
    }

    public override void OnCreate()
    {
        base.OnCreate();
        // 创建默认通知通道
        NotificationCenter.CreateNotificationChannel(new NotificationChannelRequest
        {
            Id = "default_channel",
            Name = "默认通道",
            Description = "用于展示本地通知的默认通道",
            Importance = NotificationImportance.Default
        });
    }
}

同时在AndroidManifest.xml中添加Android 13及以上所需的通知权限:

<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />

3. iOS平台权限与初始化配置

iOS需主动请求用户通知权限,并初始化通知中心:
打开iOS项目的AppDelegate.cs,修改FinishedLaunching方法:

using Plugin.LocalNotification;
using UserNotifications;

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    global::Xamarin.Forms.Forms.Init();
    LoadApplication(new App());

    // 初始化本地通知中心
    NotificationCenter.Initialize();
    
    // 请求通知权限
    UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound, (approved, error) =>
    {
        if (approved)
        {
            InvokeOnMainThread(() => UIApplication.SharedApplication.RegisterForRemoteNotifications());
        }
    });

    return base.FinishedLaunching(app, options);
}

还要在Info.plist中添加权限说明:

<key>NSNotificationAlertUsageDescription</key>
<string>需要通知权限来展示本地通知</string>
<key>NSNotificationSoundUsageDescription</key>
<string>需要声音权限来播放通知提示音</string>

完成以上配置后,重新运行项目,点击按钮即可正常触发本地通知。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 19:20:35