向 Windows 应用添加推送通知Add push notifications to your Windows app

Note

Visual Studio App Center 正在投资于对移动应用开发至关重要的新集成服务。Visual Studio App Center is investing in new and integrated services central to mobile app development. 开发人员可以使用生成测试分发服务来设置持续集成和交付管道。Developers can use Build, Test and Distribute services to set up Continuous Integration and Delivery pipeline. 部署应用后,开发人员可以使用分析诊断服务监视其应用的状态和使用情况,并使用推送服务与用户互动。Once the app is deployed, developers can monitor the status and usage of their app using the Analytics and Diagnostics services, and engage with users using the Push service. 开发人员还可以利用 Auth 对用户进行身份验证,利用数据服务在云中持久保存和同步应用数据。Developers can also leverage Auth to authenticate their users and Data service to persist and sync app data in the cloud. 立即查看 App CenterCheck out App Center today.

概述Overview

本教程介绍如何向 Windows 快速入门项目添加推送通知,以便每次插入一条记录时,向设备发送一条推送通知。In this tutorial, you add push notifications to the Windows quick start project so that a push notification is sent to the device every time a record is inserted.

如果不使用下载的快速入门服务器项目,则需要推送通知扩展包。If you do not use the downloaded quick start server project, you will need the push notification extension package. 有关详细信息,请参阅 使用适用于 Azure 移动应用的 .NET 后端服务器 SDKSee Work with the .NET backend server SDK for Azure Mobile Apps for more information.

配置通知中心Configure a Notification Hub

Azure 应用服务的移动应用功能使用 [Azure 通知中心] 发送推送内容,因此用户需为移动应用配置通知中心。The Mobile Apps feature of Azure App Service uses [Azure Notification Hubs] to send pushes, so you will be configuring a notification hub for your mobile app.

  1. Azure 门户中,转到“应用服务”,并选择应用后端。In the Azure portal, go to App Services, and then select your app back end. 在“设置”下,选择“推送”。Under Settings, select Push.

  2. 若要将通知中心资源添加到应用中,请选择“连接”。To add a notification hub resource to the app, select Connect. 可创建一个中心或连接到现有中心。You can either create a hub or connect to an existing one.

    配置中心

现在已将一个通知中心连接到移动应用后端项目。Now you have connected a notification hub to your Mobile Apps back-end project. 稍后需对此通知中心进行配置,以便连接到将内容推送到设备的平台通知系统 (PNS)。Later you configure this notification hub to connect to a platform notification system (PNS) to push to devices.

为推送通知注册应用程序Register your app for push notifications

需要将应用提交到 Microsoft Store,然后配置服务器项目与 Windows 通知服务 (WNS) 集成,以发送推送。You need to submit your app to the Microsoft Store, then configure your server project to integrate with Windows Notification Services (WNS) to send push.

  1. 在 Visual Studio 解决方案资源管理器中,右键单击 UWP 应用项目,单击“应用商店” > “将应用与应用商店关联...” 。In Visual Studio Solution Explorer, right-click the UWP app project, click Store > Associate App with the Store....

    将应用与 Microsoft Store 相关联

  2. 在向导中,单击“下一步” ,使用 Microsoft 帐户登录,在“保留新应用名称” 中键入应用的名称,然后单击“保留” 。In the wizard, click Next, sign in with your Microsoft account, type a name for your app in Reserve a new app name, then click Reserve.

  3. 成功创建应用注册后,选择新应用名称,再依次单击“下一步” 和“关联” 。After the app registration is successfully created, select the new app name, click Next, and then click Associate. 这会将所需的 Microsoft Store 注册信息添加到应用程序清单中。This adds the required Microsoft Store registration information to the application manifest.

  4. 导航到应用程序注册门户,并使用 Microsoft 帐户登录。Navigate to the Application Registration Portal and sign in with your Microsoft account. 单击上一步中关联的 Windows 应用商店应用。Click the Windows Store app you associated in the previous step.

  5. 在注册页中,记下“应用程序机密” 和“包 SID” 下的值,后面将使用这些值配置移动应用后端。In the registration page, make a note of the value under Application secrets and the Package SID, which you will next use to configure your mobile app backend.

    将应用与 Microsoft Store 相关联

    Important

    客户端密钥和程序包 SID 是重要的安全凭据。The client secret and package SID are important security credentials. 请勿将这些值告知任何人或随应用程序分发它们。Do not share these values with anyone or distribute them with your app. 将“应用程序 ID” 与机密配合使用来配置 Microsoft 帐户身份验证。The Application Id is used with the secret to configure Microsoft Account authentication.

App Center 还提供了有关为推送通知配置 UWP 应用的说明。App Center also has instructions for configuring UWP apps for push notifications.

配置后端以发送推送通知Configure the backend to send push notifications

  1. Azure 门户中,选择“浏览全部” > “应用程序服务” 。In the Azure portal, select Browse All > App Services. 然后选择“移动应用”后端。Then select your Mobile Apps back end. 在“设置”下 ,选择“应用服务推送” 。Under Settings, select App Service Push. 然后选择通知中心名称。Then select your notification hub name.

  2. 转到“Windows (WNS)” 。Go to Windows (WNS). 输入安全密钥(客户端密码)和从 Live 服务站点获取的包 SIDThen enter the Security key (client secret) and Package SID that you obtained from the Live Services site. 接下来,选择“保存” 。Next, select Save.

    设置门户中的 WNS 密钥

后端现已配置为使用 WNS 发送推送通知。Your back end is now configured to use WNS to send push notifications.

更新服务器以发送推送通知Update the server to send push notifications

使用下面与后端项目类型 —.NET 后端Node.js 后端匹配的过程。Use the procedure below that matches your backend project type—either .NET backend or Node.js backend.

.NET 后端项目.NET backend project

  1. 在 Visual Studio 中,右键单击服务器项目并单击“管理 NuGet 包” ,搜索 Microsoft.Azure.NotificationHubs,然后单击“安装” 。In Visual Studio, right-click the server project and click Manage NuGet Packages, search for Microsoft.Azure.NotificationHubs, then click Install. 这会安装通知中心客户端库。This installs the Notification Hubs client library.

  2. 展开“控制器” ,打开 TodoItemController.cs,并添加以下 using 语句:Expand Controllers, open TodoItemController.cs, and add the following using statements:

    using System.Collections.Generic;
    using Microsoft.Azure.NotificationHubs;
    using Microsoft.Azure.Mobile.Server.Config;
    
  3. 在 PostTodoItem 方法中,在调用 InsertAsync 后添加如下代码 :In the PostTodoItem method, add the following code after the call to InsertAsync:

    // Get the settings for the server project.
    HttpConfiguration config = this.Configuration;
    MobileAppSettingsDictionary settings =
        this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();
    
    // Get the Notification Hubs credentials for the Mobile App.
    string notificationHubName = settings.NotificationHubName;
    string notificationHubConnection = settings
        .Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;
    
    // Create the notification hub client.
    NotificationHubClient hub = NotificationHubClient
        .CreateClientFromConnectionString(notificationHubConnection, notificationHubName);
    
    // Define a WNS payload
    var windowsToastPayload = @"<toast><visual><binding template=""ToastText01""><text id=""1"">"
                            + item.Text + @"</text></binding></visual></toast>";
    try
    {
        // Send the push notification.
        var result = await hub.SendWindowsNativeNotificationAsync(windowsToastPayload);
    
        // Write the success result to the logs.
        config.Services.GetTraceWriter().Info(result.State.ToString());
    }
    catch (System.Exception ex)
    {
        // Write the failure result to the logs.
        config.Services.GetTraceWriter()
            .Error(ex.Message, null, "Push.SendAsync Error");
    }
    

    此代码指示通知中心在插入新项后,发送一条推送通知。This code tells the notification hub to send a push notification after a new item is insertion.

  4. 重新发布服务器项目。Republish the server project.

Node.js 后端项目Node.js backend project

  1. 设置后端项目。Set up your backend project.

  2. 将 todoitem.js 文件中的现有代码替换为以下内容:Replace the existing code in the todoitem.js file with the following:

    var azureMobileApps = require('azure-mobile-apps'),
    promises = require('azure-mobile-apps/src/utilities/promises'),
    logger = require('azure-mobile-apps/src/logger');
    
    var table = azureMobileApps.table();
    
    table.insert(function (context) {
    // For more information about the Notification Hubs JavaScript SDK,
    // see https://aka.ms/nodejshubs
    logger.info('Running TodoItem.insert');
    
    // Define the WNS payload that contains the new item Text.
    var payload = "<toast><visual><binding template=\ToastText01\><text id=\"1\">"
                                + context.item.text + "</text></binding></visual></toast>";
    
    // Execute the insert.  The insert returns the results as a Promise,
    // Do the push as a post-execute action within the promise flow.
    return context.execute()
        .then(function (results) {
            // Only do the push if configured
            if (context.push) {
                // Send a WNS native toast notification.
                context.push.wns.sendToast(null, payload, function (error) {
                    if (error) {
                        logger.error('Error while sending push notification: ', error);
                    } else {
                        logger.info('Push notification sent successfully!');
                    }
                });
            }
            // Don't forget to return the results from the context.execute()
            return results;
        })
        .catch(function (error) {
            logger.error('Error while running context.execute: ', error);
        });
    });
    
    module.exports = table;
    

    插入新的待办事项时,会发送一条包含 item.text 的 WNS toast 通知。This sends a WNS toast notification that contains the item.text when a new todo item is inserted.

  3. 编辑本地计算机上的文件时,重新发布服务器项目。When editing the file on your local computer, republish the server project.

向应用程序添加推送通知Add push notifications to your app

下一步,应用必须在启动时注册推送通知。Next, your app must register for push notifications on start-up. 已启用身份验证时,请确保用户先登录,再尝试注册推送通知。When you have already enabled authentication, make sure that the user signs-in before trying to register for push notifications.

  1. 打开 App.xaml.cs 项目文件并添加以下 using 语句:Open the App.xaml.cs project file and add the following using statements:

    using System.Threading.Tasks;
    using Windows.Networking.PushNotifications;
    
  2. 在同一文件中,将以下 InitNotificationsAsync 方法定义添加到 App 类中:In the same file, add the following InitNotificationsAsync method definition to the App class:

    private async Task InitNotificationsAsync()
    {
        // Get a channel URI from WNS.
        var channel = await PushNotificationChannelManager
            .CreatePushNotificationChannelForApplicationAsync();
    
        // Register the channel URI with Notification Hubs.
        await App.MobileService.GetPush().RegisterAsync(channel.Uri);
    }
    

    此代码从 WNS 检索应用的 ChannelURI,并将该 ChannelURI 注册到应用服务移动应用。This code retrieves the ChannelURI for the app from WNS, and then registers that ChannelURI with your App Service Mobile App.

  3. App.xaml.csOnLaunched 事件处理程序的顶部,为方法定义添加 async 修饰符,并添加对新 InitNotificationsAsync 方法的以下调用,如以下示例所示:At the top of the OnLaunched event handler in App.xaml.cs, add the async modifier to the method definition and add the following call to the new InitNotificationsAsync method, as in the following example:

    protected async override void OnLaunched(LaunchActivatedEventArgs e)
    {
        await InitNotificationsAsync();
    
        // ...
    }
    

    这保证每次启动应用程序时都注册短期的 ChannelURI。This guarantees that the short-lived ChannelURI is registered each time the application is launched.

  4. 重新生成 UWP 应用项目。Rebuild your UWP app project. 应用现在已能够接收 toast 通知。Your app is now ready to receive toast notifications.

在应用程序中测试推送通知Test push notifications in your app

  1. 右键单击 Windows 应用商店项目,单击“设为启动项目” ,并按 F5 键运行 Windows 应用商店应用。Right-click the Windows Store project, click Set as StartUp Project, then press the F5 key to run the Windows Store app.

    该应用启动后,已注册该设备以接收推送通知。After the app starts, the device is registered for push notifications.

  2. 停止 Windows 应用商店应用并对 Windows Phone 应用商店应用重复上一步操作。Stop the Windows Store app and repeat the previous step for the Windows Phone Store app.

    此时,这两个设备会注册以接收推送通知。At this point, both devices are registered to receive push notifications.

  3. 重新运行 Windows 应用商店应用,在“插入 TodoItem” 中键入文本,并单击“保存” 。Run the Windows Store app again, and type text in Insert a TodoItem, and then click Save.

    请注意,完成插入后,Windows Store 和 Windows Phone 应用会从 WNS 收到一条推送通知。Note that after the insert completes, both the Windows Store and the Windows Phone apps receive a push notification from WNS. 即使在此应用未运行时,也在 Windows Phone 上显示此通知。The notification is displayed on Windows Phone even when the app isn't running.

后续步骤Next steps

了解有关推送通知的详细信息:Learn more about push notifications:

请考虑继续学习以下教程之一:Consider continuing on to one of the following tutorials:

  • 向应用添加身份验证 了解如何使用标识提供者对应用用户进行身份验证。Add authentication to your app Learn how to authenticate users of your app with an identity provider.
  • 为应用启用脱机同步 了解如何使用移动应用后端向应用添加脱机支持。Enable offline sync for your app Learn how to add offline support your app using an Mobile App backend. 借助脱机同步,最终用户即使在没有网络连接时也能够与移动应用进行交互(查看、添加或修改数据)。Offline sync allows end-users to interact with a mobile app—viewing, adding, or modifying data—even when there is no network connection.