教程:使用 Azure 通知中心向通用 Windows 平台应用发送通知Tutorial: Send notifications to Universal Windows Platform apps by using Azure Notification Hubs

本教程介绍如何创建通知中心,以便将推送通知发送到通用 Windows 平台 (UWP) 应用。In this tutorial, you create a notification hub to send push notifications to a Universal Windows Platform (UWP) app. 创建一个空白 Windows 应用商店应用,以便使用 Windows 推送通知服务 (WNS) 接收推送通知。You create a blank Windows Store app that receives push notifications by using the Windows Push Notification Service (WNS). 然后即可使用通知中心将推送通知广播到运行应用的所有设备。Then, you use your notification hub to broadcast push notifications to all devices that are running your app.

Note

可以在 GitHub 上找到本教程的已完成代码。You can find the completed code for this tutorial on GitHub.

执行以下步骤:You take the following steps:

  • 在 Windows 应用商店中创建应用Create an app in Windows Store
  • 创建通知中心Create a Notification Hub
  • 创建示例 Windows 应用Create a sample Windows app
  • 发送测试通知Send test notifications

先决条件Prerequisites

  • Azure 订阅Azure subscription. 如果没有 Azure 订阅,可在开始前创建一个 Azure 1 元人民币试用订阅If you don't have an Azure subscription, create a Azure 1rmb-trial before you begin.
  • Microsoft Visual Studio Community 2015 或更高版本。Microsoft Visual Studio Community 2015 or later or later.
  • 已安装 UWP 应用开发工具UWP app-development tools installed
  • 有效的 Windows 应用商店帐户An active Windows Store account
  • 确认已启用“从应用和其他发送方获取通知” 设置。Confirm that Get notifications from apps and other senders setting is enabled.
    • 在计算机上启动“设置” 窗口。Launch Settings window on your computer.
    • 选择“系统” 磁贴。Select the System tile.
    • 从左侧菜单中选择“通知和操作” 。Select Notifications & actions from the left menu.
    • 确认已启用“从应用和其他发送方获取通知” 设置。Confirm that the Get notifications from apps and other senders setting is enabled. 如果未启用,请启用它。If it isn't enabled, enable it.

完成本教程是学习有关 UWP 应用的所有其他通知中心教程的先决条件。Completing this tutorial is a prerequisite for all other Notification Hubs tutorials for UWP apps.

在 Windows 应用商店中创建应用Create an app in Windows Store

要将推送通知发送到 UWP 应用,请将应用关联到 Windows 应用商店。To send push notifications to UWP apps, associate your app to the Windows Store. 然后将通知中心配置为与 WNS 集成。Then, configure your notification hub to integrate with WNS.

  1. 导航到 Windows 开发人员中心,使用 Microsoft 帐户登录,然后选择“新建应用”。 Navigate to the Windows Dev Center, sign in with your Microsoft account, and then select Create a new app.

    “新建应用”按钮

  2. 键入应用的名称,然后选择“保留产品名称”。 Type a name for your app, and then select Reserve product name. 这将为应用创建一个新的 Windows 应用商店注册。Doing so creates a new Windows Store registration for your app.

    存储应用名称

  3. 展开“应用管理”,然后依次选择“WNS/MPNS”、“Live 服务站点”。 Expand App Management, select WNS/MPNS, and then select Live Services site. 登录 Microsoft 帐户。Sign in to your Microsoft account. “应用程序注册门户”会在新选项卡中打开。 也可直接导航到应用程序注册门户,然后选择应用程序名称以访问该页。The Application Registration Portal opens in a new tab. Alternatively, you can navigate directly to the Application Registration Portal, select your application name to get to this page.

    WNS MPNS 页

  4. 记下“应用程序机密”密码和“包安全标识符(SID)”。 Note the Application Secret password and the Package security identifier (SID).

    Warning

    应用程序密钥和程序包 SID 是重要的安全凭据。The application secret and package SID are important security credentials. 请勿将这些值告知任何人或随应用程序分发它们。Do not share these values with anyone or distribute them with your app.

创建通知中心Create a Notification Hub

  1. 登录到 Azure 门户Sign in to the Azure portal.

  2. 在左侧菜单上选择“所有服务”,然后在“移动”部分中选择“通知中心”。Select All services on the left menu, and select Notification Hubs in the Mobile section. 选择服务名称旁边的星星 (*) 以将其添加到左侧菜单上的“收藏夹”部分。Select star (*) next to the service name to add it to the FAVORITES section on the left menu. 在将“通知中心”添加到“收藏夹”之后,在菜单上选择它。After Notification Hubs is added to FAVORITES, select it on the left menu.

    Azure 门户 - 选择“通知中心”

  3. 在“通知中心”页面上,在工具栏上选择“添加”。On the Notification Hubs page, select Add on the toolbar.

    通知中心 -“添加”工具栏按钮

  4. 在“通知中心”页面上,执行以下步骤:On the Notification Hub page, do the following steps:

    1. 为通知中心指定一个名称。Specify a name for the notification hub.

    2. 为命名空间指定一个名称。Specify a name for the namespace. 命名空间包含一个或多个中心。A namespace contains one or more hubs.

    3. 选择要在其中创建通知中心的位置。Select a location in which you want to create the notification hub.

    4. 选择一个现有资源组,或者为新资源组输入一个名称。Select an existing resource group or enter a name for the new resource group.

    5. 选择“创建” 。Select Create.

      Azure 门户 - 设置通知中心属性

  5. 选择“通知”(钟形图标),然后选择“转到资源”。Select Notifications (Bell icon), and select Go to resource. 还可以刷新“通知中心”页中的列表,然后选择通知中心。You can also refresh the list in the Notification Hubs page, and select your notification hub.

    Azure 门户 - 通知 -> 转到资源

  6. 从列表中选择“访问策略”。Select Access Policies from the list. 记下向你提供的两个连接字符串。Note the two connection strings that are available to you. 稍后在处理推送通知时需要它们。You need them to handle push notifications later.

    Important

    在应用程序中使用 DefaultFullSharedAccessSignature。Do NOT use the DefaultFullSharedAccessSignature in your application. 这只能在后端使用。This is meant to be used in your back-end only.

    Azure 门户 - 通知中心连接字符串

配置中心的 WNS 设置Configure WNS settings for the hub

  1. 在“通知设置”类别中选择“Windows (WNS)”。 In the NOTIFICATION SETTINGS category, select Windows (WNS).

  2. 输入在前一部分记下的“包 SID”和“安全密钥”的值。 Enter values for Package SID and Security Key you noted from the previous section.

  3. 单击工具栏上的“保存” 。Click Save on the toolbar.

    “包 SID”框和“安全密钥”框

通知中心现在已配置为使用 WNS。Your notification hub is now configured to work with WNS. 你有了用于注册应用和发送通知的连接字符串。You have the connection strings to register your app and send notifications.

创建示例 Windows 应用Create a sample Windows app

  1. 在 Visual Studio 中打开“文件” 菜单,选择“新建” ,然后选择“项目” 。In Visual Studio, open the File menu, select New, and then select Project.

  2. 在“新建项目”对话框中完成以下步骤: In the New Project dialog, complete the following steps:

    1. 展开“Visual C#”。 Expand Visual C#.

    2. 选择“Windows Universal”。 Select Windows Universal.

    3. 选择“空白应用(通用 Windows)”。 Select Blank App (Universal Windows).

    4. 输入项目的名称Enter a name for the project.

    5. 选择“确定” 。Select OK.

      “新建项目”对话框

  3. 接受目标最低平台版本的默认值,然后选择“确定”。 Accept the defaults for the target and minimum platform versions, and select OK.

  4. 在“解决方案资源管理器”中,右键单击 Windows 应用商店应用项目,选择“应用商店”,然后选择“将应用与应用商店关联”。 In Solution Explorer, right-click the Windows Store app project, select Store, and then select Associate App with the Store. 此时会显示“将应用与 Windows 应用商店关联”向导。 The Associate Your App with the Windows Store wizard appears.

  5. 在向导中,使用 Microsoft 帐户登录。In the wizard, sign in with your Microsoft account.

  6. 选择在第 2 步中注册的应用,选择“下一步”,然后选择“关联” 。Select the app that you registered in step 2, select Next, and then select Associate. 这会将所需的 Windows 应用商店注册信息添加到应用程序清单中。Doing so adds the required Windows Store registration information to the application manifest.

  7. 在 Visual Studio 中,右键单击该解决方案,并选择“管理 NuGet 包”。 In Visual Studio, right-click the solution, and then select Manage NuGet Packages. 此时会打开“管理 NuGet 包” 窗口。The Manage NuGet Packages window opens.

  8. 在搜索框中,输入 WindowsAzure.Messaging.Managed,选择“安装” ,并接受使用条款。In the search box, enter WindowsAzure.Messaging.Managed, select Install, and accept the terms of use.

    “管理 NuGet 包”窗口

    此操作使用 Microsoft.Azure.NotificationHubs NuGet 包下载、安装并添加对 Azure 通知中心库的引用。This action downloads, installs, and adds a reference to the Azure Notification Hubs library for Windows by using the Microsoft.Azure.NotificationHubs NuGet package.

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

    using Windows.Networking.PushNotifications;
    using Microsoft.WindowsAzure.Messaging;
    using Windows.UI.Popups;
    
  10. 在项目的 App.xaml.cs 文件中,找到 App 类并添加以下 InitNotificationsAsync 方法定义:In the project's App.xaml.cs file, locate the App class, and add the following InitNotificationsAsync method definition:

    private async void InitNotificationsAsync()
    {
        var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
    
        var hub = new NotificationHub("<your hub name>", "<Your DefaultListenSharedAccessSignature connection string>");
        var result = await hub.RegisterNativeAsync(channel.Uri);
    
        // Displays the registration ID so you know it was successful
        if (result.RegistrationId != null)
        {
            var dialog = new MessageDialog("Registration successful: " + result.RegistrationId);
            dialog.Commands.Add(new UICommand("OK"));
            await dialog.ShowAsync();
        }
    }
    

    此代码从 WNS 检索应用的通道 URI,并将该通道 URI 注册到用户的通知中心。This code retrieves the channel URI for the app from WNS, and then registers that channel URI with your notification hub.

    Note

    hub name 占位符替换为出现在 Azure 门户中的通知中心的名称。Replace the hub name placeholder with the name of the notification hub that appears in the Azure portal. 另外,使用在之前部分中从通知中心的“访问策略”页获取的 DefaultListenSharedAccessSignature 连接字符串替换连接字符串占位符 。Also replace the connection string placeholder with the DefaultListenSharedAccessSignature connection string that you obtained from the Access Polices page of your notification hub in a previous section.

  11. App.xaml.csOnLaunched 事件处理程序的上方,添加对新 InitNotificationsAsync 方法的以下调用:At the top of the OnLaunched event handler in App.xaml.cs, add the following call to the new InitNotificationsAsync method:

    InitNotificationsAsync();
    

    此操作保证每次启动应用程序时都在通知中心注册通道 URI。This action guarantees that the channel URI is registered in your notification hub each time the application launches.

  12. 若要运行应用,请按键盘的 F5 键。To run the app, press the keyboard's F5 key. 此时会显示包含注册密钥的对话框。A dialog box containing the registration key will display. 若要关闭对话框,请单击“确定”。 To close the dialog, click OK.

    注册成功

应用现在已能够接收 toast 通知。Your app is now ready to receive toast notifications.

发送测试通知Send test notifications

可以通过在 Azure 门户中发送通知来快速测试在应用中接收通知。You can quickly test receiving notifications in your app by sending notifications in the Azure portal.

  1. 在 Azure 门户中切换到“概览”选项卡,然后在工具栏上选择“测试性发送”。 In the Azure portal, switch to the Overview tab, and select Test Send on the toolbar.

    “测试性发送”按钮

  2. 在“测试性发送”窗口中执行以下操作: In the Test Send window, do the following actions:

    1. 对于“平台”,请选择“Windows” 。 For Platforms, select Windows.

    2. 对于“通知类型”,请选择“Toast”。 For Notification Type, select Toast.

    3. 选择“发送”。 Select Send.

      “测试发送”窗格

  3. 请在窗口底部的“结果”列表中查看“发送”操作的结果。 See the result of the Send operation in the Result list at the bottom of the window. 此外还会看到一条警报消息。You also see an alert message.

    “发送”操作的结果

  4. 可看到通知消息:在桌面上测试消息You see the notification message: Test message on your desktop.

    通知消息

后续步骤Next steps

使用门户或控制台应用将广播通知发送到所有 Windows 设备。You have sent broadcast notifications to all your Windows devices by using the portal or a console app. 若要了解如何向特定的设备推送通知,请转到以下教程:To learn how to push notifications to specific devices, advance to the following tutorial: