Add push notifications to your Apache Cordova app

Overview

In this tutorial, you add push notifications to the Apache Cordova quickstart project so that a push notification is sent to the device every time a record is inserted.

If you do not use the downloaded quickstart server project, you need the push notification extension package. For more information, see Work with the .NET back-end server SDK for Mobile Apps.

Prerequisites

This tutorial assumes that you have an Apache Cordova application that was developed with Visual Studio 2015. This device should run on Google Android Emulator, an Android device, a Windows device, or an iOS device.

To complete this tutorial, you need:

Configure a notification hub

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. 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.

    Configure a hub

Now you have connected a notification hub to your Mobile Apps back-end project. Later you configure this notification hub to connect to a platform notification system (PNS) to push to devices.

Watch a video showing steps in this section.

Update the server project

In this section, you update code in your existing Mobile Apps back-end project to send a push notification every time a new item is added. This process is powered by the template feature of Azure Notification Hubs, which enables cross-platform pushes. The various clients are registered for push notifications using templates, and a single universal push can get to all client platforms.

Choose one of the following procedures that matches your back-end project type—either .NET back end or Node.js back end.

.NET back-end project

  1. In Visual Studio, right-click the server project. Then select Manage NuGet Packages. Search for Microsoft.Azure.NotificationHubs, and then select Install. This process installs the Notification Hubs library for sending notifications from the back end.

  2. In the server project, open Controllers > TodoItemController.cs. Then add the following using statements:

    using System.Collections.Generic;
    using Microsoft.Azure.NotificationHubs;
    using Microsoft.Azure.Mobile.Server.Config;
    
  3. 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 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");
    }
    

    This process sends a template notification that contains the item.Text when a new item is inserted.

  4. Republish the server project.

Node.js back-end project

  1. Set up your backend project.

  2. Replace the existing code in todoitem.js with the following code:

    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;  
    

    This process sends a template notification that contains the item.text when a new item is inserted.

  3. When you edit the file on your local computer, republish the server project.

Modify your Cordova app

To ensure that your Apache Cordova app project is ready to handle push notifications, install the Cordova push plugin plus any platform-specific push services.

Update the Cordova version in your project.

If your project uses a version of Apache Cordova that's earlier than version 6.1.1, update the client project. To update the project, take the following steps:

  • To open the configuration designer, right-click config.xml.
  • Select the Platforms tab.
  • In the Cordova CLI text box, select 6.1.1.
  • To update the project, select Build, and then select Build Solution.

Install the push plugin

Apache Cordova applications do not natively handle device or network capabilities. These capabilities are provided by plugins that are published either on npm or on GitHub. The phonegap-plugin-push plugin handles network push notifications.

You can install the push plugin in one of the following ways:

From the command-prompt:

Run the following command:

cordova plugin add phonegap-plugin-push

From within Visual Studio:

  1. In Solution Explorer, open the config.xml file. Next, select Plugins > Custom. Then select Git as the installation source.

  2. Enter https://github.com/phonegap/phonegap-plugin-push as the source.

    Open the config.xml file in Solution Explorer

  3. Select the arrow next to the installation source.

  4. In SENDER_ID, if you already have a numeric project ID for the Google Developer Console project, you can add it here. Otherwise, enter a placeholder value, such as 777777. If you are targeting Android, you can update this value in the config.xml file later.

    Note

    As of version 2.0.0, google-services.json needs to be installed in the root folder of your project to configure the sender ID. For more information, see the installation documentation.

  5. Select Add.

The push plugin is now installed.

Install the device plugin

Follow the same procedure you used to install the push plugin. Add the Device plugin from the Core plugins list. (To find it, select Plugins > Core.) You need this plugin to obtain the platform name.

Register your device when the application starts

Initially, we include some minimal code for Android. Later you can modify the app to run on iOS or Windows 10.

  1. Add a call to registerForPushNotifications during the callback for the sign-in process. Alternatively, you can add it at the bottom of the onDeviceReady method:

    // 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);
    

    This example shows calling registerForPushNotifications after authentication succeeds. You can call registerForPushNotifications() as often as is required.

  2. Add the new registerForPushNotifications method as follows:

    // 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) In the preceding code, replace Your_Project_ID with the numeric project ID for your app from the Google Developer Console.

(Optional) Configure and run the app on Android

Complete this section to enable push notifications for Android.

Enable Firebase Cloud Messaging

Since you are targeting the Google Android platform initially, you must enable Firebase Cloud Messaging.

  1. Sign in to the Firebase console. Create a new Firebase project if you don't already have one.

  2. After you create your project, select Add Firebase to your Android app.

    Add Firebase to your Android app

  3. On the Add Firebase to your Android app page, take the following steps:

    1. For Android package name, copy the value of your applicationId in your application's build.gradle file. In this example, it's com.fabrikam.fcmtutorial1app.

      Specify the package name

    2. Select Register app.

  4. Select Download google-services.json, save the file into the app folder of your project, and then select Next.

    Download google-services.json

  5. Make the following configuration changes to your project in Android Studio.

    1. In your project-level build.gradle file (<project>/build.gradle), add the following statement to the dependencies section.

      classpath 'com.google.gms:google-services:4.0.1'
      
    2. In your app-level build.gradle file (<project>/<app-module>/build.gradle), add the following statements to the dependencies section.

      implementation 'com.google.firebase:firebase-core:16.0.8'
      implementation 'com.google.firebase:firebase-messaging:17.3.4'
      
    3. Add the following line to the end of the app-level build.gradle file after the dependencies section.

      apply plugin: 'com.google.gms.google-services'
      
    4. Select Sync now on the toolbar.

      build.gradle configuration changes

  6. Select Next.

  7. Select Skip this step.

    Skip the last step

  8. In the Firebase console, select the cog for your project. Then select Project Settings.

    Select Project Settings

  9. If you haven't downloaded the google-services.json file into the app folder of your Android Studio project, you can do so on this page.

  10. Switch to the Cloud Messaging tab at the top.

  11. Copy and save the Server key for later use. You use this value to configure your hub.

Configure the Mobile App back end to send push requests using FCM

  1. In the Azure portal, select Browse All > App Services. Then select your Mobile Apps back end.
  2. Under Settings, select Push. Then select Configure push notification services.
  3. Go to Google (GCM). Enter the FCM legacy server key that you obtained from the Firebase console, and then select Save.

Your service is now configured to work with Firebase Cloud Messaging.

Configure your Cordova app for Android

In your Cordova app, open config.xml. Then replace Your_Project_ID with the numeric project ID for your app from the Google Developer Console.

<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>

Open index.js. Then update the code to use your numeric project ID.

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

Configure your Android device for USB debugging

Before you can deploy your application to your Android Device, you need to enable USB debugging. Take the following steps on your Android phone:

  1. Go to Settings > About phone. Then tap the Build number until developer mode is enabled (about seven times).
  2. Back in Settings > Developer Options, enable USB debugging. Then connect your Android phone to your development PC with a USB cable.

We tested this using a Google Nexus 5X device running Android 6.0 (Marshmallow). However, the techniques are common across any modern Android release.

Install Google Play Services

The push plugin relies on Android Google Play Services for push notifications.

  1. In Visual Studio, select Tools > Android > Android SDK Manager. Then expand the Extras folder. Check the appropriate boxes to ensure that each of the following SDKs is installed:

    • Android 2.3 or higher
    • Google Repository revision 27 or higher
    • Google Play Services 9.0.2 or higher
  2. Select Install Packages. Then wait for the installation to finish.

The current required libraries are listed in the phonegap-plugin-push installation documentation.

Test push notifications in the app on Android

You can now test push notifications by running the app and inserting items in the TodoItem table. You can test from the same device or from a second device, as long as you are using the same back end. Test your Cordova app on the Android platform in one of the following ways:

  • On a physical device: Attach your Android device to your development computer with a USB cable. Instead of Google Android Emulator, select Device. Visual Studio deploys the application to the device and runs the application. You can then interact with the application on the device.

    Screen-sharing applications such as Mobizen can assist you in developing Android applications. Mobizen projects your Android screen to a web browser on your PC.

  • On an Android emulator: There are additional configuration steps that are required when you're using an emulator.

    Make sure you are deploying to a virtual device that has Google APIs set as the target, as shown in the Android Virtual Device (AVD) manager.

    Android Virtual Device Manager

    If you want to use a faster x86 emulator, install the HAXM driver, and then configure the emulator to use it.

    Add a Google account to the Android device by selecting Apps > Settings > Add account. Then follow the prompts.

    Add a Google account to the Android device

    Run the todolist app as before and insert a new todo item. This time, a notification icon is displayed in the notification area. You can open the notification drawer to view the full text of the notification.

    View notification

(Optional) Configure and run on iOS

This section is for running the Cordova project on iOS devices. If you aren't working with iOS devices, you can skip this section.

Install and run the iOS remote build agent on a Mac or cloud service

Before you can run a Cordova app on iOS using Visual Studio, go through the steps in the iOS setup guide to install and run the remote build agent.

Make sure you can build the app for iOS. The steps in the setup guide are required for building the app for iOS from Visual Studio. If you do not have a Mac, you can build for iOS by using the remote build agent on a service like MacInCloud. For more information, see Run your iOS app in the cloud.

Note

Xcode 7 or greater is required to use the push plugin on iOS.

Find the ID to use as your App ID

Before you register your app for push notifications, open config.xml in your Cordova app, find the id attribute value in the widget element, and then copy it for later use. In the following XML, the ID is 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">

Later, use this identifier when you create an App ID on Apple's developer portal. If you create a different App ID on the developer portal, you must take a few extra steps later in this tutorial. The ID in the widget element must match the App ID on the developer portal.

Register the app for push notifications on Apple's developer portal

Watch a video showing similar steps

Configure Azure to send push notifications

  1. On your Mac, launch Keychain Access. On the left navigation bar, under Category, open My Certificates. Find the SSL certificate that you downloaded in the previous section, and then disclose its contents. Select only the certificate (do not select the private key). Then export it.
  2. In the Azure portal, select Browse All > App Services. Then select your Mobile Apps back end.
  3. Under Settings, select App Service Push. Then select your notification hub name.
  4. Go to Apple Push Notification Services > Upload Certificate. Upload the .p12 file, selecting the correct Mode (depending on whether your client SSL certificate from earlier is production or sandbox). Save any changes.

Your service is now configured to work with push notifications on iOS.

Verify that your App ID matches your Cordova app

If the App ID that you created in your Apple Developer Account already matches the ID of the widget element in the config.xml file, you can skip this step. However, if the IDs don't match, take the following steps:

  1. Delete the platforms folder from your project.
  2. Delete the plugins folder from your project.
  3. Delete the node_modules folder from your project.
  4. Update the id attribute of the widget element in the config.xml file to use the app ID that you created in your Apple developer account.
  5. Rebuild your project.
Test push notifications in your iOS app
  1. In Visual Studio, make sure that iOS is selected as the deployment target. Then select Device to run the push notifications on your connected iOS device.

    You can run the push notifications on an iOS device that's connected to your PC with iTunes. The iOS Simulator does not support push notifications.

  2. Select the Run button or F5 in Visual Studio to build the project and start the app in an iOS device. Then select OK to accept push notifications.

    Note

    The app requests confirmation for push notifications during the first run.

  3. In the app, type a task, and then select the plus (+) icon.

  4. Verify that a notification was received. Then select OK to dismiss the notification.

(Optional) Configure and run on Windows

This section describes how to run the Apache Cordova app project on Windows 10 devices (the PhoneGap push plugin is supported on Windows 10). If you are not working with Windows devices, you can skip this section.

Register your Windows app for push notifications with WNS

To use the Store options in Visual Studio, select a Windows target from the Solution Platforms list, such as Windows-x64 or Windows-x86. (Avoid Windows-AnyCPU for push notifications.)

  1. In Visual Studio Solution Explorer, right-click the Windows Store app project. Then select Store > Associate App with the Store.

    Associate app with Windows Store

  2. In the wizard, select Next. Then sign in with your Microsoft account. In Reserve a new app name, type a name for your app, and then select Reserve.

  3. After the app registration is successfully created, select the new app name. Select Next, and then select Associate. This process adds the required Windows Store registration information to the application manifest.

  4. Repeat steps 1 and 3 for the Windows Phone Store app project by using the same registration you previously created for the Windows Store app.

  5. Go to the Windows Dev Center, and then sign in with your Microsoft account. In My apps, select the new app registration. Then expand Services > Push notifications.

  6. On the Push notifications page, under Windows Push Notification Services (WNS) and Microsoft Azure Mobile Apps, select Live Services site. Make a note of the values of the Package SID and the current value in Application Secret.

    App setting in the developer center

    Important

    The application secret and package SID are important security credentials. Don't share these values with anyone or distribute them with your app.

Watch a video showing similar steps

Configure the notification hub for WNS

  1. 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. Go to Windows (WNS). Then enter the Security key (client secret) and Package SID that you obtained from the Live Services site. Next, select Save.

    Set the WNS key in the portal

Your back end is now configured to use WNS to send push notifications.

Configure your Cordova app to support Windows push notifications

Open the configuration designer by right-clicking config.xml. Then select View Designer. Next, select the Windows tab, and then select Windows 10 under Windows Target Version.

To support push notifications in your default (debug) builds, open the build.json file. Then copy the "release" configuration to your debug configuration.

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

After the update, the build.json file should contain the following code:

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

Build the app and verify that you have no errors. Your client app should now register for the notifications from the Mobile Apps back end. Repeat this section for every Windows project in your solution.

Test push notifications in your Windows app

In Visual Studio, make sure that a Windows platform is selected as the deployment target, such as Windows-x64 or Windows-x86. To run the app on a Windows 10 PC that's hosting Visual Studio, choose Local Machine.

  1. Select the Run button to build the project and start the app.

  2. In the app, type a name for a new todoitem, and then select the plus (+) icon to add it.

Verify that a notification is received when the item is added.

Next steps

Learn how to use the following SDKs: