如何在MacOS上用C#开发Avalonia应用发送用户通知?
在Avalonia应用中实现MacOS系统通知的可行方案
方案1:直接调用MacOS原生UserNotifications框架(推荐)
MacOS的系统通知由UserNotifications框架提供,可通过.NET平台调用或Objective-C绑定实现,无需依赖已废弃的Xamarin。
步骤1:配置通知权限
在应用的Info.plist中添加权限描述,否则系统会拒绝通知请求:
<key>NSUserNotificationUsageDescription</key> <string>需要发送通知提醒您相关事项</string> <key>UNUserNotificationUsageDescription</key> <string>需要发送通知提醒您相关事项</string>
注:NSUserNotificationUsageDescription对应MacOS 10.13及更早版本,UNUserNotificationUsageDescription对应10.14及更新版本
步骤2:实现C#调用逻辑
借助.NET的ObjectiveCRuntime组件(包含在.NET for MacOS包中),绑定UserNotifications框架核心类后即可调用:
using Foundation; using UserNotifications; // 在应用启动时请求通知权限 public async Task RequestNotificationPermission() { var center = UNUserNotificationCenter.Current; var options = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound; var status = await center.RequestAuthorizationAsync(options); if (!status.Granted) { // 处理权限被拒绝的场景 return; } } // 发送自定义通知 public void SendMacNotification(string title, string body) { var content = new UNMutableNotificationContent(); content.Title = title; content.Body = body; content.Sound = UNNotificationSound.Default; var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(0.1, false); var request = UNNotificationRequest.FromIdentifier(Guid.NewGuid().ToString(), content, trigger); UNUserNotificationCenter.Current.AddNotificationRequest(request, (error) => { if (error != null) { // 处理通知发送失败的情况 } }); }
注:需确保项目引用Microsoft.NET.Sdk.MacOS或包含UserNotifications绑定的NuGet包,部分旧版Xamarin.Mac绑定可在.NET 6+环境中兼容使用,也可自行生成绑定
方案2:通过终端命令发送基础通知(快速实现)
若无需复杂交互功能,可直接调用MacOS的osascript命令发送简易通知:
using System.Diagnostics; public void SendSimpleNotification(string title, string body) { var script = $"display notification \"{body}\" with title \"{title}\""; var process = new Process { StartInfo = new ProcessStartInfo { FileName = "/usr/bin/osascript", Arguments = $"-e '{script}'", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true } }; process.Start(); process.WaitForExit(); }
限制:无法自定义图标、添加按钮动作,仅支持基础标题与内容展示
方案3:扩展Avalonia通知接口
基于Avalonia提供的INotificationManager接口,实现MacOS专属的通知逻辑:
using Avalonia.Platform; public class MacNotificationManager : INotificationManager { public void ShowNotification(Notification notification) { // 复用方案1的发送逻辑 SendMacNotification(notification.Title, notification.Message); } // 实现接口其他方法(如取消通知等) public void CancelNotification(string notificationId) { // 补充取消通知的逻辑 } public void CancelAllNotifications() { // 补充批量取消通知的逻辑 } }
在应用启动时注册该实现:
AvaloniaLocator.CurrentMutable.Bind<INotificationManager>().ToConstant(new MacNotificationManager());
内容的提问来源于stack exchange,提问作者DemonExposer
相关产品推荐
相关产品推荐

