概述
在本教程中,将推送通知添加到 Windows 快速入门 项目,以便在每次插入记录时向设备发送推送通知。
如果不使用下载的快速入门服务器项目,则需要推送通知扩展包。 有关详细信息 ,请参阅使用适用于 Azure 移动应用的 .NET 后端服务器 SDK 。
配置通知中心
Azure 应用服务的移动应用功能使用 Azure 通知中心 发送推送,因此你将为移动应用配置通知中心。
在 Azure 门户中,转到 应用服务,然后选择应用后端。 在 设置中,选择 推送。
若要向应用添加通知中心资源,请选择 连接。 可以创建中心或连接到现有中心。
现在,已将通知中心连接到移动应用后端项目。 稍后,请将此通知中心配置为连接到平台通知系统(PNS),以推送到设备。
为推送通知注册应用程序
需要将应用提交到 Microsoft 应用商店,然后将服务器项目配置为与 Windows 推送通知服务(WNS) 集成以发送推送。
在 Visual Studio 解决方案资源管理器中,右键单击 UWP 应用项目,单击 “应用商店>与应用商店关联应用...”。
在向导中,单击“ 下一步”,使用Microsoft帐户登录,在 “保留新应用名称”中键入应用的名称,然后单击“ 保留”。
成功创建应用注册后,选择新的应用名称,单击“ 下一步”,然后单击“ 关联”。 这会将所需的微软应用商店注册信息添加到应用程序清单。
导航到 应用程序注册门户 并使用Microsoft帐户登录。 单击在上一步中关联的 Windows 应用商店应用。
在注册页中,记下 应用程序机密 和 包 SID 下的值,接下来将使用该值来配置移动应用后端。
重要
客户端机密和包 SID 是重要的安全凭据。 请勿将这些值告知任何人或随应用程序分发它们。 应用程序 ID 与机密一起使用,用于配置Microsoft帐户身份验证。
App Center 还介绍了如何为推送通知配置 UWP 应用。
配置后端以发送推送通知
在 Azure 门户中,选择“”浏览所有>应用服务。 然后选择移动应用后端。 在 设置中,选择 应用服务推送。 然后选择通知中心名称。
转到 Windows (WNS)。 然后输入从 Live Services 站点获取的 安全密钥(客户端密码)和 包 SID。 接下来,选择 保存。
后端现已配置为使用 WNS 发送推送通知。
更新服务器以发送推送通知
使用以下与后端项目类型匹配的过程: .NET 后端 或 Node.js 后端。
.NET 后端项目
在 Visual Studio 中,右键单击服务器项目,然后单击“ 管理 NuGet 包”,搜索 Microsoft.Azure.NotificationHubs,然后单击“ 安装”。 这会安装通知中心客户端库。
展开 Controllers,打开 TodoItemController.cs 文件,并添加以下 using 语句:
using System.Collections.Generic; using Microsoft.Azure.NotificationHubs; using Microsoft.Azure.Mobile.Server.Config;
在 PostTodoItem 方法中,在调用 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"); }
此代码告知通知中心在插入新项后发送推送通知。
重新发布服务器项目。
Node.js 后端项目
搭建你的后端项目。
将 todoitem.js 文件中的现有代码替换为以下内容:
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 通知。
在本地计算机上编辑文件时,重新发布服务器项目。
向应用添加推送通知
接下来,应用必须在启动时注册推送通知。 启用身份验证后,请确保用户在尝试注册推送通知之前登录。
打开 App.xaml.cs 项目文件并添加以下
using
语句:using System.Threading.Tasks; using Windows.Networking.PushNotifications;
在同一文件中,将以下 InitNotificationsAsync 方法定义添加到 App 类:
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 注册到应用服务移动应用。
在 App.xaml.cs 的 OnLaunched 事件处理程序顶部,将异步修饰符添加到方法定义,并向新的 InitNotificationsAsync 方法添加以下调用,如以下示例所示:
protected async override void OnLaunched(LaunchActivatedEventArgs e) { await InitNotificationsAsync(); // ... }
这可以保证每次启动应用程序时都会注册生存期较短的 ChannelURI。
重新生成 UWP 应用项目。 应用现在已能够接收 toast 通知。
在应用中测试推送通知
右键单击 Windows 应用商店项目,单击“ 设为启动项目”,然后按 F5 键运行 Windows 应用商店应用。
应用启动后,设备将注册以接收推送通知。
停止 Windows 应用商店应用,并为 Windows Phone 应用商店应用重复上一步。
此时,这两个设备都已注册以接收推送通知。
再次运行 Windows 应用商店应用,并在 “插入 TodoItem”中键入文本,然后单击“ 保存”。
请注意,插入完成后,Windows 应用商店和 Windows Phone 应用都会收到来自 WNS 的推送通知。 即使应用未运行,通知也会显示在 Windows Phone 上。
后续步骤
详细了解推送通知:
- 如何使用 Azure 移动应用的托管客户端 模板使你可以灵活地发送跨平台推送和本地化推送。 了解如何注册模板。
- 诊断推送通知问题 有各种原因导致通知可能会被删除或最终不会在设备上出现。 本主题介绍如何分析和找出推送通知失败的根本原因。
请考虑继续学习以下教程之一: