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

如何在.NET MAUI Windows桌面应用中实现推送通知?

在.NET MAUI Windows桌面应用中实现推送通知

是的,.NET MAUI支持Windows桌面应用的推送通知,核心依赖Windows Notification Service (WNS)——Windows平台原生的推送服务。以下是具体实现步骤:

1. 前期准备

  • 前往Microsoft Store开发者中心注册你的应用,获取Package Security Identifier (SID)和客户端密钥,这两个信息是调用WNS API的必要凭证。
  • 确保你的.NET MAUI项目的Windows目标框架设置为net6.0-windows10.0.19041.0或更高版本。

2. 配置Windows平台推送通道

在Platforms/Windows/App.xaml.cs中添加推送通道注册逻辑:

using Windows.Networking.PushNotifications;
using Windows.UI.Notifications;

namespace YourAppName.WinUI;

public partial class App : MauiWinUIApplication
{
    protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();

    protected override void OnLaunched(LaunchActivatedEventArgs args)
    {
        base.OnLaunched(args);
        RegisterPushNotificationChannel();
    }

    private async void RegisterPushNotificationChannel()
    {
        try
        {
            PushNotificationChannel channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
            // 将channel.Uri发送到你的后端服务器,用于后续推送
            System.Diagnostics.Debug.WriteLine($"推送通道URI: {channel.Uri}");

            // 监听通知到达事件
            channel.PushNotificationReceived += Channel_PushNotificationReceived;
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"注册通道失败: {ex.Message}");
        }
    }

    private void Channel_PushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args)
    {
        if (args.NotificationType == PushNotificationType.Toast)
        {
            // 显示Toast通知
            ToastNotificationManager.CreateToastNotifier().Show(args.ToastNotification);
            // 标记已处理,避免系统默认处理
            args.Cancel = false;
        }
    }
}

3. 处理通知交互(可选)

如果需要处理用户点击通知的操作,可以在App.xaml.cs中重写OnActivated方法:

protected override void OnActivated(IActivatedEventArgs args)
{
    if (args is ToastNotificationActivatedEventArgs toastArgs)
    {
        // 获取通知中的参数
        string argsString = toastArgs.Argument;
        // 根据参数跳转对应页面或执行逻辑
        MainPage?.DisplayAlert("通知点击", $"收到参数: {argsString}", "确定");
    }
    base.OnActivated(args);
}

4. 发送测试通知

你可以通过PowerShell调用WNS API发送测试通知,示例脚本(替换你的SID、密钥和通道URI):

$sid = "你的应用SID"
$clientSecret = "你的客户端密钥"
$channelUri = "你的推送通道URI"

# 获取OAuth令牌
$tokenUrl = "https://login.microsoftonline.com/$sid/oauth2/token"
$tokenBody = @{
    grant_type = "client_credentials"
    client_id = $sid
    client_secret = $clientSecret
    scope = "https://wns.windows.com/.default"
}
$tokenResponse = Invoke-RestMethod -Uri $tokenUrl -Method Post -Body $tokenBody
$accessToken = $tokenResponse.access_token

# 发送Toast通知
$notificationBody = @"
<toast>
    <visual>
        <binding template="ToastGeneric">
            <text>测试推送</text>
            <text>这是来自WNS的.NET MAUI桌面通知</text>
        </binding>
    </visual>
</toast>
"@

Invoke-RestMethod -Uri $channelUri -Method Post -Headers @{
    "Authorization" = "Bearer $accessToken"
    "Content-Type" = "application/xml"
} -Body $notificationBody

注意事项

  • 应用必须打包为MSIX才能正常使用WNS,调试时可通过Visual Studio的"打包并部署"功能测试。
  • 如果需要后台处理通知(比如应用未运行时接收),需配置后台任务,并在应用清单中声明对应能力。

内容的提问来源于stack exchange,提问作者Francisco Jose GOÑI

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 08:43:22