将推送通知添加到 Apache Cordova 应用

概述

本教程介绍如何向 Apache Cordova 快速入门项目添加推送通知,以便每次插入一条记录时,都向设备发送一条推送通知。

如果不使用下载的快速入门服务器项目,则需要推送通知扩展包。 有关详细信息,请参阅使用适用于移动应用的 .NET 后端服务器 SDK

先决条件

本教程假设已使用 Visual Studio 2015 开发了一个 Apache Cordova 应用程序。 此设备应在 Google Android 模拟器、Android 设备、Windows 设备或 iOS 设备上运行。

要完成本教程,需要:

配置通知中心

Azure 应用服务的移动应用功能使用 Azure 通知中心发送推送内容,因此用户需为移动应用配置通知中心。

  1. Azure 门户中,转到“应用服务”,并选择应用后端。 在“设置”下,选择“推送”

  2. 若要将通知中心资源添加到应用中,请选择“连接”。 可以创建一个中心,也可以连接到一个现有的中心。

    Configure a hub

现在已将通知中心连接到移动应用后端项目。 稍后需对此通知中心进行配置,以便连接到将内容推送到设备的平台通知系统 (PNS)。

观看视频,其中显示了本部分中的步骤

更新服务器项目

在本部分中,更新现有移动应用后端项目中的代码,以便在每次添加新项目时发送推送通知。 此过程由 Azure 通知中心的模板功能提供支持,允许跨平台推送。 各种客户端使用模板注册推送通知,因此只需单个通用推送即可将内容发送到所有客户端平台。

选择其中一个与后端项目类型(.NET 后端Node.js 后端)匹配的过程。

.NET 后端项目

  1. 在 Visual Studio 中,右键单击服务器项目。 然后选择“管理 NuGet 包”。 搜索 Microsoft.Azure.NotificationHubs,并选择“安装” 。 此过程将安装通知中心库,以便从后端发送通知。

  2. 在服务器项目中,打开“控制器”>“TodoItemController.cs”。 然后,添加以下 using 语句:

    using System.Collections.Generic;
    using Microsoft.Azure.NotificationHubs;
    using Microsoft.Azure.Mobile.Server.Config;
    
  3. 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 a new Notification Hub client.
    NotificationHubClient hub = NotificationHubClient
    .CreateClientFromConnectionString(notificationHubConnection, notificationHubName);
    
    // Send the message so that all template registrations that contain "messageParam"
    // receive the notifications. This includes APNS, GCM, WNS, and MPNS template registrations.
    Dictionary<string,string> templateParams = new Dictionary<string,string>();
    templateParams["messageParam"] = item.Text + " was added to the list.";
    
    try
    {
        // Send the push notification and log the results.
        var result = await hub.SendTemplateNotificationAsync(templateParams);
    
        // 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");
    }
    

    插入新项时,此过程将发送一个包含 item.Text 的模板通知。

  4. 重新发布服务器项目。

Node.js 后端项目

  1. 设置后端项目。

  2. 将 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 template payload.
    var payload = '{"messageParam": "' + context.item.text + '" }';  
    
    // 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 template notification.
                context.push.send(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 的模板通知。

  3. 编辑本地计算机上的文件时,请重新发布服务器项目。

修改 Cordova 应用

确保 Apache Cordova 应用项目已准备就绪,可通过安装 Cordova 推送插件和任何平台特定的推送服务来处理推送通知。

更新项目中的 Cordova 版本。

如果项目使用早于版本 6.1.1 的 Apache Cordova 版本,请更新客户端项目。 若要更新项目,请执行以下步骤:

  • 若要打开配置设计器,请右键单击 config.xml
  • 选择 “平台 ”选项卡。
  • 在“Cordova CLI”文本框中选择“6.1.1”。
  • 若要更新项目,请依次选择“生成”、“生成解决方案”。

安装推送插件

Apache Cordova 应用程序不支持在本地处理设备或网络功能。 这些功能由发布在 npm 或 GitHub 上的插件提供。 phonegap-plugin-push 插件可处理网络推送通知。

可通过下面其中一种方式安装推送插件:

从命令提示符:

运行以下命令:

cordova plugin add phonegap-plugin-push

从 Visual Studio 内部:

  1. 在“解决方案资源管理器”中,打开 config.xml 文件。 接下来,选择 “插件>自定义”。 然后选择“Git”作为安装源。

  2. 输入 https://github.com/phonegap/phonegap-plugin-push 作为源。

    Open the config.xml file in Solution Explorer

  3. 选择安装源旁边的箭头。

  4. SENDER_ID 中,如果已经有 Google Developer Console 项目的数值项目 ID,可将其添加在此处。 否则,请输入一个占位符值,如 777777。 如果以 Android 为目标,可稍后在 config.xml 文件中更新该值。

    注意

    从版本 2.0.0 开始,需要在项目根文件夹中安装 google-services.json 才能配置发送方 ID。 有关详细信息,请参阅安装文档

  5. 选择 添加

现已安装推送插件。

安装设备插件

按照用于安装推送插件的相同步骤进行操作。 从“核心插件”列表添加“设备”插件。 (若要找到它,请选择 Plugins>Core.) 需要此插件才能获取平台名称。

在应用程序启动时注册设备

最初,我们会针对 Android 提供一些最少的代码。 稍后,可以修改应用以便在 iOS 或 Windows 10 上运行。

  1. 在登录过程的回调期间,添加对 registerForPushNotifications 的调用。 或者,可以在 onDeviceReady 方法的底部添加该调用:

    // Log in to the service.
    client.login('google')
        .then(function () {
            // Create a table reference.
            todoItemTable = client.getTable('todoitem');
    
            // Refresh the todoItems.
            refreshDisplay();
    
            // Wire up the UI Event Handler for the Add Item.
            $('#add-item').submit(addItemHandler);
            $('#refresh').on('click', refreshDisplay);
    
                // Added to register for push notifications.
            registerForPushNotifications();
    
        }, handleError);
    

    此示例演示在身份验证成功之后调用 registerForPushNotifications。 可以根据需要经常调用 registerForPushNotifications()

  2. 按如下所示添加新的 registerForPushNotifications 方法:

    // Register for push notifications. Requires that phonegap-plugin-push be installed.
    var pushRegistration = null;
    function registerForPushNotifications() {
        pushRegistration = PushNotification.init({
            android: { senderID: 'Your_Project_ID' },
            ios: { alert: 'true', badge: 'true', sound: 'true' },
            wns: {}
        });
    
    // Handle the registration event.
    pushRegistration.on('registration', function (data) {
        // Get the native platform of the device.
        var platform = device.platform;
        // Get the handle returned during registration.
        var handle = data.registrationId;
        // Set the device-specific message template.
        if (platform == 'android' || platform == 'Android') {
            // Register for GCM notifications.
            client.push.register('gcm', handle, {
                mytemplate: { body: { data: { message: "{$(messageParam)}" } } }
            });
        } else if (device.platform === 'iOS') {
            // Register for notifications.
            client.push.register('apns', handle, {
                mytemplate: { body: { aps: { alert: "{$(messageParam)}" } } }
            });
        } else if (device.platform === 'windows') {
            // Register for WNS notifications.
            client.push.register('wns', handle, {
                myTemplate: {
                    body: '<toast><visual><binding template="ToastText01"><text id="1">$(messageParam)</text></binding></visual></toast>',
                    headers: { 'X-WNS-Type': 'wns/toast' } }
            });
        }
    });
    
    pushRegistration.on('notification', function (data, d2) {
        alert('Push Received: ' + data.message);
    });
    
    pushRegistration.on('error', handleError);
    }
    
  3. (Android) 在上述代码中,将 Your_Project_ID 替换成 Google Developer Console 中应用的数值项目 ID。

(可选)在 Android 上配置并运行应用

完成此部分以启用 Android 的推送通知。

启用 Firebase Cloud Messaging

由于我们最初面向的是 Google Android 平台,因此必须启用 Firebase Cloud Messaging。

  1. 登录到 Firebase 控制台。 如果还没有 Firebase 项目,创建一个新项目。

  2. 创建项目后,选择“向 Android 应用添加 Firebase”。

    Add Firebase to your Android app

  3. 在“将 Firebase 添加到 Android 应用”页上,执行以下步骤:

    1. 对于“Android 程序包名称”,请在应用程序的 build.gradle 文件中复制 applicationId 的值。 在此示例中,它是 com.fabrikam.fcmtutorial1app

      Specify the package name

    2. 选择“注册应用”。

  4. 选择“下载 google-services.json”,将该文件保存到项目的 app 文件夹中,然后选择“下一步”

    Download google-services.json

  5. 在 Android Studio 中对你的项目进行以下配置更改

    1. 在项目级 build.gradle 文件 (<project>/build.gradle) 中,向 dependencies 部分中添加以下语句。

      classpath 'com.google.gms:google-services:4.0.1'
      
    2. 在应用级 build.gradle 文件 (<project>/<app-module>/build.gradle) 中,向 dependencies 部分中添加以下语句。

      implementation 'com.google.firebase:firebase-core:16.0.8'
      implementation 'com.google.firebase:firebase-messaging:17.3.4'
      
    3. 在应用级 build.gradle 文件的末尾,在 dependencies 部分后面添加以下行。

      apply plugin: 'com.google.gms.google-services'
      
    4. 在工具栏上选择“立即同步”。

      build.gradle configuration changes

  6. 选择“下一步” 。

  7. 选择“跳过此步骤”

    Skip the last step

  8. 在 Firebase 控制台中,选择与项目相对应的齿轮图标。 然后,选择“项目设置”。

    Select Project Settings

  9. 如果尚未将 google-services.json 文件下载到你的 Android Studio 项目的 app 文件夹中,则可以在此页面上执行此操作。

  10. 切换到顶部的“Cloud Messaging”选项卡。

  11. 复制并保存服务器密钥以供将来使用。 此值将用于配置中心。

使用 FCM 配置移动应用后端以发送推送请求

  1. Azure 门户中,选择“浏览全部”>“应用程序服务”。 然后选择“移动应用”后端。
  2. 在“设置”下,选择“推送”。 选择“配置推送通知服务”
  3. 转到“Google (GCM)”。 输入从 Firebase 控制台获取的 FCM 旧服务器密钥,并选择“保存”

现在,服务已配置为使用 Firebase Cloud Messaging。

配置适用于 Android 的 Cordova 应用

在 Cordova 应用中,打开 config.xml。 然后,将 Your_Project_ID 替换为 Google Developer Console 中应用的数值项目 ID。

<plugin name="phonegap-plugin-push" version="1.7.1" src="https://github.com/phonegap/phonegap-plugin-push.git">
    <variable name="SENDER_ID" value="Your_Project_ID" />
</plugin>

打开 index.js。 然后更新代码以使用数值项目 ID。

pushRegistration = PushNotification.init({
    android: { senderID: 'Your_Project_ID' },
    ios: { alert: 'true', badge: 'true', sound: 'true' },
    wns: {}
});

配置 Android 设备以进行 USB 调试

需要启用 USB 调试才能将应用程序部署到 Android 设备。 在 Android 手机上执行以下步骤:

  1. 转到 设置>About 电话。 然后不断点击“内部版本号”(大约 7 次),直到启用开发人员模式。
  2. 回到 设置>Developer 选项中,启用 USB 调试。 然后使用 USB 线缆将 Android 手机连接到开发电脑。

已使用运行 Android 6.0 (Marshmallow) 的 Google Nexus 5X 设备对此进行了测试。 但是,任何新式 Android 版本中都普遍具有此技术。

安装 Google Play Services

推送插件依赖 Android Google Play 服务发送推送通知。

  1. 在Visual Studio中,选择“工具>Android>Android SDK 管理器。 展开“Extras”文件夹。 勾选相应的复选框,确保安装以下每个 SDK:

    • Android 2.3 或更高版本
    • Google 存储库修订 27 或更高版本
    • Google Play Services 9.0.2 或更高版本
  2. 选择“安装程序包”。 等待安装完成。

phonegap-plugin-push 安装文档中列出了当前需要的库。

在 Android 应用中测试推送通知

现在,可以通过运行该应用并将项插入 TodoItem 表中测试推送通知。 只要使用同一后端,就可以在同一设备或另一台设备中进行测试。 通过下面其中一种方式在 Android 平台上测试 Cordova 应用:

  • 在物理设备上:使用 USB 线缆将 Android 设备连接到开发计算机。 不是使用 Google Android 模拟器,而是选择“设备”。 Visual Studio 会将应用程序部署到设备,并运行应用程序。 可以随后在该设备上与该应用程序进行交互。

    屏幕共享应用程序(如 Mobizen)可以帮助你开发 Android 应用程序。 Mobizen 会将 Android 屏幕投影到电脑上的 Web 浏览器。

  • 在 Android 模拟器中:使用模拟器时,还需要其他配置步骤。

    请确保部署到将 Google API 设置为目标的虚拟设备,如 Android 虚拟设备 (AVD) 管理器所示。

    Android Virtual Device Manager

    如果想要使用更快的 x86 模拟器,请安装 HAXM 驱动程序并配置模拟器以使用它。

    通过选择“应用>设置>Add 帐户,将 Google 帐户添加到Android设备。 然后遵照提示操作。

    Add a Google account to the Android device

    像以前一样运行 todolist 应用并插入一个新的 todo 项。 此时通知区域中会显示一个通知图标。 可以打开通知抽屉查看通知的完整文本。

    View notification

(可选)配置并在 iOS 上运行

本部分介绍了在 iOS 设备上运行 Cordova 项目。 如果不使用 iOS 设备,可以跳过本部分。

在 Mac 或云服务上安装并运行 iOS 远程生成代理

在使用 Visual Studio 在 iOS 上运行 Cordova 应用之前,请完成安装并运行远程生成代理iOS安装指南中的步骤。

请确保可以生成 iOS 应用。 需要执行安装指南中的步骤,通过 Visual Studio 生成适用于 iOS 的应用。 如果没有 Mac,可以使用服务(如 MacInCloud)中的远程生成代理针对 iOS 生成。 有关详细信息,请参阅在云中运行 iOS 应用

注意

在 iOS 上使用推送插件需要 Xcode 7 或更高版本。

查找要作为应用程序 ID 的 ID

在注册应用以推送通知前,在 Cordova 应用中打开 config.xml,找到小组件元素中的 id 属性值,复制该值以供将来使用。 在以下 XML 中,ID 是 io.cordova.myapp7777777

<widget defaultlocale="en-US" id="io.cordova.myapp7777777"
    version="1.0.0" windows-packageVersion="1.1.0.0" xmlns="https://www.w3.org/ns/widgets"
    xmlns:cdv="http://cordova.apache.org/ns/1.0" xmlns:vs="https://schemas.microsoft.com/appx/2014/htmlapps">

稍后,在 Apple 开发人员门户创建应用程序 ID 时,使用此标识符。 如果在开发人员门户上创建不同的应用 ID,则必须执行本教程后面所述的一些额外步骤。 小组件元素中的 ID 必须与开发人员门户中的应用 ID 匹配。

在 Apple 的开发人员门户上为推送通知注册应用

  • 为应用注册应用 ID。 创建显式应用 ID (不是通配符应用 ID) ,对于捆绑 ID,请使用Xcode快速入门项目中的确切捆绑 ID。 此外,必须选择“推送通知”选项。
  • 接下来,为了准备配置推送通知,请创建“开发”或“分发”SSL 证书。

观看显示类似步骤的视频

配置 Azure 以发送推送通知

  1. 在 Mac 上启动“Keychain Access”。 在左侧导航栏中的“类别”下,打开“我的证书”。 找到已在前一部分下载的 SSL 证书,并公开其内容。 仅选择证书(不选择私钥)。 然后将其导出
  2. Azure 门户中,选择“浏览全部”>“应用程序服务”。 然后选择“移动应用”后端。
  3. 在“设置”下,选择“应用服务推送”。 然后选择通知中心名称。
  4. 转到“Apple Push Notification 服务”>“上传证书” 。 上传 .p12 文件,选择正确的模式(具体取决于此前的客户端 SSL 证书是生产证书还是沙盒证书)。 保存任何更改。

现在,服务已配置为在 iOS 上使用通知中心。

验证应用程序 ID 是否匹配 Cordova 应用

如果 Apple 开发人员帐户中创建的应用程序 ID 已与 config.xml 中的小组件元素的 ID 匹配,则可以跳过此步骤。 但是,如果 ID 不匹配,请执行以下步骤:

  1. 从项目中删除平台文件夹。
  2. 从项目中删除插件文件夹。
  3. 从项目中删除 node_modules 文件夹。
  4. 更新config.xml文件中小组件元素的 ID 属性,以使用在 Apple 开发人员帐户中创建的应用 ID。
  5. 重新生成项目。
在 iOS 应用中测试推送通知
  1. 在 Visual Studio 中,确保已选择“iOS”作为部署目标。 然后选择“设备”,以便在连接的 iOS 设备上运行推送通知。

    可以在使用 iTunes 连接到电脑的 iOS 设备上运行推送通知。 iOS 模拟器不支持推送通知。

  2. 在 Visual Studio 中选择“运行”按钮或按 F5 生成项目并在 iOS 设备中启动应用, 然后选择“确定”接受推送通知。

    注意

    首次运行时,应用会请求对推送通知进行确认。

  3. 在应用中,键入一项任务,并选择加号 (+) 图标。

  4. 确认收到了通知。 然后选择“确定”以关闭通知。

(可选)配置并在 Windows 上运行

本部分介绍如何在 Windows 10 设备上运行 Apache Cordova 应用项目( Windows 10 支持 PhoneGap 推送插件)。 如果不使用 Windows 设备,可以跳过本部分。

向 WNS 注册用于推送通知的 Windows 应用

若要在 Visual Studio 中使用应用商店选项,从解决方案平台列表中选择 Windows 目标,如 Windows-x64Windows-x86。 (避免使用 Windows-AnyCPU 发送推送通知。)

  1. 在 Visual Studio 解决方案资源管理器中,右键单击 Windows 应用商店应用项目。 然后选择“应用商店”>“将应用与应用商店关联”。

    Associate app with Windows Store

  2. 在向导中,选择“下一步”。 然后,使用 Microsoft 帐户登录。 在“保留新应用名称”中为应用键入一个名称,然后选择“保留”

  3. 成功创建应用注册后,选择新应用名称。 选择“下一步”,然后选择“关联”。 此过程会将所需的 Windows 应用商店注册信息添加到应用程序清单中。

  4. 使用之前为 Windows 应用商店应用创建的相同注册,对 Windows Phone 商店应用重复步骤 1 和 3。

  5. 转到 Windows 开发人员中心,并使用 Microsoft 帐户登录。 在“我的应用”中,选择新的应用注册。 然后展开“服务”>“推送通知”。

  6. 在“推送通知”页上,在“Windows 推送通知服务(WNS)和 Microsoft Azure 移动应用”下,选择“Live 服务站点”。 记下“包 SID”的值和“应用程序密钥”中的当前值。

    App setting in the developer center

    重要

    应用程序机密和程序包 SID 是重要的安全凭据。 不要将这些值告诉任何人,也不要随应用分发它们。

观看显示类似步骤的视频

为 WNS 配置通知中心

  1. Azure 门户中,选择“浏览全部”>“应用程序服务”。 然后选择“移动应用”后端。 在“设置”下,选择“应用服务推送”。 然后选择通知中心名称。

  2. 转到“Windows (WNS)”。 输入安全密钥(客户端密码)和从 Live 服务站点获取的包 SID。 接下来,选择“保存”

    Set the WNS key in the portal

后端现已配置为使用 WNS 发送推送通知。

配置 Cordova 应用,以支持 Windows 推送通知

若要打开配置设计器,请右键单击“config.xml”。 然后选择“视图设计器”。 接下来,选择“Windows”选项卡,并选择“Windows 目标版本”下的“Windows 10”。

若要支持默认 (调试) 生成中的推送通知,请打开 build.json 文件。 然后将“版本”配置复制到调试配置。

"windows": {
    "release": {
        "packageCertificateKeyFile": "res\\native\\windows\\CordovaApp.pfx",
        "publisherId": "CN=yourpublisherID"
    }
}

更新后, build.json 文件应包含以下代码:

"windows": {
    "release": {
        "packageCertificateKeyFile": "res\\native\\windows\\CordovaApp.pfx",
        "publisherId": "CN=yourpublisherID"
        },
    "debug": {
        "packageCertificateKeyFile": "res\\native\\windows\\CordovaApp.pfx",
        "publisherId": "CN=yourpublisherID"
        }
    }

生成应用并确保没有错误。 客户端应用现在应从移动应用后端注册通知。 对于解决方案中的每个 Windows 项目,重复此部分的操作。

在 Windows 应用中测试推送通知

在 Visual Studio 中,确保已选择 Windows 平台作为部署目标,例如 Windows-x64Windows-x86。 若要在托管 Visual Studio 的 Windows 10 电脑上运行该应用,请选择“本地计算机”

  1. 选择“运行”按钮生成项目并启动应用程序。

  2. 在应用中,为新 todoitem 键入一个名称,并选择加号 (+) 图标添加该项。

确认在添加该项目时收到了通知。

后续步骤

  • 有关推送通知的信息,请参阅通知中心
  • 如果尚未这样做,请通过将身份验证添加到 Apache Cordova 应用来继续学习该教程。

了解如何使用以下 SDK: