Appstore Blogs

Appstore Blogs

Want the latest?

appstore topics

Recent Posts

Archive

Showing posts tagged with Push Notification

June 17, 2014

Russell Beattie

The Cordova Push Notifications Plugin is a project that lets hybrid web app developers create apps that respond to custom push notifications from services such as the Apple Push Notification Service (APNS), Google Cloud Messaging (GCM) and most recently Amazon Device Messaging (ADM). This enables hybrid web apps to be notified when an online service has information for it - such as a personal message, sports score or appointment - even if the app is not currently running.

If you're unfamiliar with Amazon Device Messaging, it's a simple, efficient and free messaging service from Amazon that lets developers send push notifications from the cloud to Kindle Fire devices, helping app creators more deeply engage with their customers by keeping them up to date and involved.

You can find the plugin, and complete documentation on the Cordova PushPlugin Github repository, but here are the basics on getting started using the plugin for Amazon Fire OS.

Overview

Macintosh HD:Users:beattier:Desktop:cordova_adm:adm-cordova.png

Amazon Device Messaging works similarly to the other push notification services and has three main parts involved in the process:

  • Your server sends notifications (messages, updates, scores, etc.) to the ADM Servers to be routed to the client apps.
  • ADM Servers queue and route notifications to client apps.
  • Your  app receives the notification on a device.

The Cordova Push Notifications Plugin allows your hybrid web app to use JavaScript to register with the ADM Server and receive notification events when sent from your server.

Please note that ADM only works with Fire OS devices and the Cordova Amazon Fire OS platform target. For more information about setting up a Fire OS Cordova project, please see our earlier blog post,  Building Higher Performance Cordova-based Fire OS Apps By Implementing Amazon WebView Support.

ADM Credentials

In order for your server to send notifications to your app, both the server and app, need to be authenticated/registered with the ADM Server:

  1. Create a sample Cordova app for the Amazon Fire OS platform so you have the app name, package name and the debug build ready.
  2. Create a developer account on the Amazon Developer Portal if you don't already have one
  3. Fill out the New App Submission form and turn Device Messaging switch to ON.
  4. Create Security Profile to obtain ADM credentials for your app.
    Note: For development, you can use the MD5 signature of the debug apk created by Cordova build process found in <project_path>/platforms/amazon-fireos/ant-build.

You will need to make note of the OAuth Credentials (Client ID and Client Secret) to be used on your notifications server and the API Key to be used in your client app. These can be found on the Security Profile Management pages in the areas marked in green below:

Macintosh HD:Users:beattier:Desktop:cordova_adm:credentials.png

Below is a graphic which shows a general overview of the authentication process and how your client app and your server to authenticate and register with the ADM Server:

Macintosh HD:Users:beattier:Desktop:cordova_adm:authentication2.png

Install Push Notifications Plugin

Once you have created an initial Cordova app for the Amazon Fire OS platform, use the standard plugin command from your project directory to install the Push Notifications Plugin.

cordova plugin add https://github.com/phonegap-build/PushPlugin.git

This will download the plugin and install it in your app's project directory. There will be a new folder called <com.phonegap.plugins.PushPlugin> inside your project's plugin directory.  This folder contains: the source files for the plugin, an Example directory that has a sample web app you can use to receive ADM notifications on the client, and a Node.js script you can use to send notifications, simulating what a server would normally do.

Before you can start testing notifications, you will need to follow the steps below to download and install the ADM support libraries and add the proper credentials to your project.

Install Amazon Device Messaging Library

The push notifications plugin needs the support files found in the ADM API. Follow these steps to download the SDK and install the library files in your Cordova project:

  1. Download the Amazon Mobile App SDK and unzip.
  2. Create a folder called ext_libs in <project_path>/platforms/amazon-fireos folder.
  3. Copy amazon-device-messaging-x.x.x.jar into the <project_path>/platforms/amazon-fireos/ext_libs
  4. Create a new text file called ant.properties in the <project_path>/platforms/amazon-fireos folder, and add a java.compiler.classpath entry pointing at the ADM library. For example:
    java.compiler.classpath=./ext_libs/amazon-device-messaging-1.0.1.jar
    
  5. Create a new text file called api_key.txt in the <project_path>/platforms/amazon-fireos/assets folder, and copy the API Key you obtained in the Credentials section above. Note: Be careful not to add any extra spaces to the text file.

Create Sample App

Here's a basic web app that can be used to test receiving notifications on the client. Create new index.html and index.js files in your project's www directory and copy the markup/code below.

The index.html page is simply a container for the messages to be displayed on the device:

index.html:

<!DOCTYPE html>
<html>
<head>
	<title>ADM Test</title>
</head>
<body>
	<h1>ADM Test</h1>
	<pre id="container" style="word-wrap:break-word"></pre>
	<script src="cordova.js"></script>
	<script src="index.js"></script>
</body>
</html>

The index.js script uses the PushPlugin to display notifications received on the client.

index.js:

var container = document.getElementById("container");
var pushNotification;

document.addEventListener("deviceready", handleDeviceReady, true);

function handleDeviceReady(){

    pushNotification = window.plugins.pushNotification;
    pushNotification.register( handleSuccess, handleError, {"ecb":"handleNotification"});

}

function handleNotification(e) {

    log("**** EVENT RECEIVED: " + e.event );

    if(e.event == "registered"){
        if(e.regid.length > 0){
            log("REGISTRATION ID:  <br>" + e.regid);
            log("<a href=\"mailto:?subject=ADM%20Registration%20ID&body=" + encodeURIComponent(e.regid) + "\">Email Registration ID</a>");
        }
    } else if(e.event == "message"){
        if ( e.foreground ) {
            log("FOREGROUND NOTIFICATION");
        } else {
            if ( e.coldstart )  {
                log("COLDSTART NOTIFICATION");
            } else {
                log("BACKGROUND NOTIFICATION");
            }
        }
        log("MESSAGE: " + e.payload.message );
        log("TIME: " + e.payload.timeStamp );
        log("URL: " + e.payload.url );
    } else if(e.event == "error"){
        log("ERROR: " + e.msg );
    }
}

function handleSuccess(result) {
    log("Plugin Success: " + result );
}

function handleError(error) {
    log("Plugin Error: " + error );
}

function log(msg){
    container.innerHTML += msg + "<br>";
    console.log(msg);
}

Notes about the JavaScript:

  • The handleDeviceReady method will use the pushNotification object to register the client with the ADM Server. This requires that the api_key.txt file contains the correct information.
  • The Registration ID that is returned to the client is used by your server to send notifications to the correct device/app combination. The ID is very long, so there's a link to email the ID to yourself to be used in testing.
  • The notification event has a flag to tell your app whether it was in the foreground, background or not started when the notification arrived.
  • The ADM notification event contains a payload object consisting of arbitrary fields populated by your server. In this example, the server will send a message, timestamp and URL, but each app can be different.
  • If there are errors with authentication or other issues such as connectivity problems, the app should log to the screen any error messages sent to your app.

Once you have your client app ready, use Cordova's command line to install the app on your test device (usually using the "cordova run" command). If you have set up everything correctly, the app will start, authenticate with the ADM Server and display the Registration ID unique to your device/app to be used by your notifications server.

Test ADM Notifications

Normally, you will have a dedicated server which sends app notifications via the ADM Server, using the Registration ID to uniquely identify each instance of your app running on a specific device. Your app will be responsible for getting the Registration ID from each registered device to your server.

For testing purposes, we are instead going to use the pushADM.js Node script found in the <project_path>/plugins/com.phonegap.plugins.PushPlugin/Example/server folder. This script acts in place of your server, authenticating with Amazon and then pushing notifications to the ADM Servers to be delivered to your app. (Node is a prerequisite for Cordova, so you should already have it installed on your system.)

Before we can use the script, we need to add in your OAuth Credentials and Registration ID. Here is a snippet from the top part of the test script that you will be editing:

pushADM.js:

// Client ID and Client Secret received from ADM portal
var CLIENT_ID = ""; 
var CLIENT_SECRET = "";

// Registration ID, received on device after it registers with ADM server
var REGISTRATION_IDS = [""];

// Message payload to be sent to client
var payload = {
        data: {
            message: "PushPlugin works!!",
            url: "http://www.amazon.com",
            timeStamp: new Date().toISOString()
        },
        consolidationKey: "my app",
        expiresAfter: 3600
};
...

Edit the pushADM.js script :

  1. Copy the OAuth credentials - Client ID and Client Secret - you obtained in the Credentials section above into the CLIENT_ID and CLIENT_SECRET variables.
  2. Copy one or more Registration IDs from a registered app into the REGISTRATION_IDS array. Note: You can fill this var with IDs from multiple devices for testing. Using the sample app above, you can email the Registration ID to yourself and then copy/paste it into the test script.
  3. Optionally edit the payload object with custom values to be sent to your app.

Run the pushADM.js script from a command line using Node:

node pushADM.js

The result on the command line should be a series of log messages which shows the script authenticating with the ADM Server and then sending a message. The app running on your Kindle Fire should then instantly show the message if it is in the foreground, or add a notification alert to the top bar if it is in the background or not running. You can run this script as many times as you need to test your app.

Here is what the of the sample web app above looks like after receiving a notification:

Macintosh HD:Users:beattier:Desktop:cordova_adm:Screenshot_2014-05-28-14-17-15.png

Summary

The steps above should give you a good start towards implementing ADM push notifications into your app. Once you have your app working, it will be very easy to customize the notification payload as you need to create compelling new apps and services for your customers.

If you have trouble, please make sure to check out the links below for information and support:

Good luck!

-Russ

 

 

Want the latest?

appstore topics

Recent Posts

Archive