This post originally appeared on the Icenium.com blog.

Overview

What are push notifications?

Push notifications are messages sent from an application server to a specific device using the vendor infrastructure. Typically, push notifications are used to notify an application to update its data. For example, push notifications are sent when a feed has been updated, a message has been received, or a new appointment has been made. For more information about push notifications, see Push technology.

Why do we need push notifications?

Push notifications are designed to preserve phone resources. If an app queries the server every 10 seconds, this uses up precious battery life and bandwidth. In fact, an iOS app cannot poll a server continuously because there is no true multitasking. Instead, the user needs to actually start the application to update it.

General overview

There are three components in the life cycle of a push notification: the actual application, the OS vendor servers (or a third-party mediator), and the application server. Here's how it works:

  1. The application registers for push notifications with the OS. (Under the hood, the OS contacts the vendor push servers and requests a token.)
  2. The OS returns the token to the application.
  3. The token is sent to the application server.
  4. The application server uses the token to send push notifications to the device.

Let's Bring Push Notifications to Life

With the Cordova-based PushPlugin plugin, we will develop the push notification module of a promotional app. The sample app is designed to run on iOS and Android, and to display promotional text in a single paragraph. To run and test the app, we will also create a simple application server and a web form that sends verbatim promotional text to the application. We will be using the Apple Push-Notification Service (APN) for iOS, and Google Cloud Messaging (GCM) for Android.

Bear this in mind – because push notifications are unreliable, you should avoid using them to transport data. Instead, use them to let your app know that an update is needed.

Application Server

Let's start our project by creating an application server with Node.js. (Node.js is becoming more and more popular and you can check out why here.) This sample application server was tested on Windows 7 64-bit and Mac OS 10.7 with the latest stable Node.js installed – but you should be able to run it on any OS that supports Node.js.

Here are the requirements for our server:

  • Accept token from device and store it for later use.
  • Host and run a very simple web form to send messages. (NOTE: To keep the code as simple and clear as possible, we will not add any security features.)
  • Send push notifications for new promotions to all registered devices.
  • Store promotional text submitted with the web form.

Our simplified HTTP server will listen on port 80 and answer requests with status code 200 and an empty body. (Just browse to localhost in your favorite browser and look at the node process console output.)

NOTE:

  • Turn off IIS, if running.
  • Running Node.js is as simple as running node server.js in the command line.
  • Running on ports below 1024 may require admin/root privileges, so you can alter the port as needed, or use sudo, etc. to run the server.js module below.
  1. var http = require('http'); //include http module
  2. var url = require('url'); //include url module
  3. var allDevices = []; //variable will hold all registered devices
  4. http.createServer(function(request, response) { //the callback is called for each HTTP request received
  5.     var currentDate = new Date(); //log received requests
  6.     console.log("#Received request. " + currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds());
  7.     request.setEncoding('utf8'); //set encoding to utf8
  8.     response.writeHead(200, {
  9.         'Content-Type': 'text/plain'
  10.     }); //return 200 with text/plain MIME type
  11.     response.end(); //end the response
  12. }).listen(80); //start the server on port 80
  13. console.log('Server running at http://127.0.0.1:80'); //log that the server is running

Before trying to communicate with any devices, let's get the dirty work done and create form.html - our simple web form:

  1. <!DOCTYPE html>
  2. <html>
  3.         <head>
  4.                 <title>Send Message to All Devices</title>
  5.         </head>
  6.         <body>
  7.                 <h2>Send Message to All Devices</h2>
  8.                 <form action="setPromotion" method="post">
  9.                         <label>Message:</label>
  10.                         <input type="text" name="text"></input>
  11.                         <input type="submit" value="Submit">
  12.                 </form>
  13.         </body>
  14. </html>

Next, we need to configure how our server handles the form. In our project, the server sends the form when called without a path. When the server is called with the "/setPromotion" path, the server responds with the promotional text that is currently stored in the form:

  1. var http = require('http');
  2. var url = require('url');
  3. var fs = require('fs'); //include fs module
  4. var allDevices = [];
  5. var promotionText; //variable will hold the promotional text
  6. //the function will return the web form named form.html
  7. function returnForm(response) {
  8.     fs.readFile('form.html', function(err, html) {
  9.         response.writeHeader(200, {
  10.             "Content-Type": "text/html",
  11.             "Content-Lenght": html.length
  12.         });
  13.         response.write(html);
  14.         response.end();
  15.     });
  16. }
  17. //the function is called when the form is submitted
  18. function setPromotion(request, response) {
  19.     request.on('data', function(data) { //on "data" event, read the contents of the form
  20.         promotionText = decodeURI(data.slice(data.indexOf("=") + 1));
  21.         promotionText = promotionText.replace(/\+/g, ' '); //remove old encoding of + with spaces
  22.         //notify devices with push notification that a promotion is available
  23.     })
  24.     response.writeHeader(200, {
  25.         "Content-Type": "text/html"
  26.     });
  27.     response.write("Successfully added to queue."); //display confirmation message for the submission
  28.     response.end();
  29. }
  30. http.createServer(function(request, response) {
  31.     var currentDate = new Date();
  32.     console.log("#Received request. " + currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds());
  33.     request.setEncoding('utf8');
  34.     var parsedUrl = url.parse(request.url); //parse the url and use switch to create routes
  35.     switch (parsedUrl.href) {
  36.         case "/":
  37.             returnForm(response);
  38.             break;
  39.         case "/setPromotion":
  40.             setPromotion(request, response);
  41.             break;
  42.         default:
  43.             response.writeHeader(200);
  44.             response.end();
  45.             break;
  46.     }
  47. }).listen(80);
  48. console.log('Server running at http://127.0.0.1:80');

In your browser, you can test to see if the form appears and if using it correctly persists the message to the promotionText variable on the server. To track errors, you can add console.log anywhere you need it in the code. 
The next step is to implement adding and removing devices, and querying for promotional text.

In the code below, we add routes for device registration and for retrieving promotional text. We also register the "/getPromotion" route that serves our promotion in JSON format. 
To register, devices send their device token and platform in JSON format to the server.

  1. var http = require('http');
  2. var url = require('url');
  3. var fs = require('fs');
  4. var allDevices = [];
  5. var promotionText;
  6. function returnForm(response) {
  7.     fs.readFile('form.html', function(err, html) {
  8.         response.writeHeader(200, {
  9.             "Content-Type": "text/html",
  10.             "Content-Lenght": html.length
  11.         });
  12.         response.write(html);
  13.         response.end();
  14.     });
  15. }
  16. function setPromotion(request, response) {
  17.     request.on('data', function(data) {
  18.         promotionText = decodeURI(data.slice(data.indexOf("=") + 1));
  19.         promotionText = promotionText.replace(/\+/g, ' ');
  20.     })
  21.     response.writeHeader(200, {
  22.         "Content-Type": "text/html"
  23.     });
  24.     response.write("Successfully added to queue.");
  25.     response.end();
  26. }
  27. //the function will be used for device registration
  28. function registerDevice(request, response) {
  29.     request.on('data', function(data) {
  30.         var device = JSON.parse(data); //parse the message sent from the device
  31.         for (var i = allDevices.length - 1; i >= 0; i--) {
  32.             if (allDevices[i].token == device.token) //if device is already registered, do not register it
  33.             return;
  34.         };
  35.         allDevices.push(device);
  36.         console.log("#Registered device with platform:" + device.platform);
  37.     })
  38.     response.writeHeader(200, {
  39.         "Content-Type": "application/json"
  40.     });
  41.     response.write(JSON.stringify({
  42.         success: true
  43.     })); //send simple success
  44.     response.end();
  45. }
  46. //return the promotional text wrapped inside a json object
  47. function getPromotion(request, response) {
  48.     var responseObject = {
  49.         text: promotionText
  50.     };
  51.     var responseString = JSON.stringify(responseObject);
  52.     response.writeHeader(200, {
  53.         "Content-Type": "application/json",
  54.         "Content-Lenght": responseString.length
  55.     });
  56.     response.write(responseString);
  57.     response.end();
  58. }
  59. http.createServer(function(request, response) {
  60.     var currentDate = new Date();
  61.     console.log("#Received request. " + currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds());
  62.     request.setEncoding('utf8');
  63.     var parsedUrl = url.parse(request.url);
  64.     switch (parsedUrl.href) {
  65.         case "/":
  66.             returnForm(response);
  67.             break;
  68.         case "/setPromotion":
  69.             setPromotion(request, response);
  70.             break;
  71.         case "/register":
  72.             registerDevice(request, response);
  73.             break;
  74.         case "/getPromotion":
  75.             getPromotion(request, response);
  76.             break;
  77.         default:
  78.             response.writeHeader(200);
  79.             response.end();
  80.             break;
  81.     }
  82. }).listen(80);
  83. console.log('Server running at http://127.0.0.1:80');

Now let's start developing some of the device-side functionality, so that we can check if our application server is implemented correctly.

App code

Let's begin by creating a new jQuery project in Graphite. From Project Properties, we'll add PushPlugin to the project and include a reference to PushNotification.js in index.html
Then, we create a file named push.js in the js folder and include a reference to it in index.html
Here is how the script tags in your index.html should look:

  1. <script src="cordova.js" type="text/javascript"></script>
  2. <script src="Plugins/PushPlugin/PushNotification.js"></script>
  3. <script src="jquery-mobile/jquery-1.8.2.min.js" type="text/javascript"></script>
  4. <script src="jquery-mobile/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
  5. <script src="http://maps.google.com/maps/api/js?sensor=true"></script>
  6. <script src="js/hello-world.js" type="text/javascript"></script>
  7. <script src="js/push.js" type="text/javascript"></script>

Because there are differences in the code for iOS vs Android, we will implement the push notifications functionality separately.

iOS

  • First, we get the local value of the Push Notification JS object.
  • Next, we create success and failure functions for getting the APN token. We will send the token to our application server.
  • Then, we will subscribe to device ready event and register to get badges, sounds, and alerts for our application.
  • We also tell the PushPlugin to notify us when we get a notificationon by invokingpushCallbacks.onNotificationAPN . We will implement this later when we have actual push notifications to handle.
  1. //wrap the entire functionality in a function to create a namespace
  2. (function() {
  3.     var pushNotification = window.plugins.pushNotification;
  4.     var apnSuccessfulRegistration = function(token) {
  5.         alert("Successfully got a token:" + token);
  6.     }
  7.     var apnFailedRegistration = function(error) {
  8.         alert("Error: " + error.toString());
  9.     }
  10.     var deviceReady = function() {
  11.         if (device.platform == "iOS") {
  12.             pushNotification.register(apnSuccessfulRegistration,
  13.             apnFailedRegistration, {
  14.                 "badge": "true",
  15.                 "sound": "true",
  16.                 "alert": "true",
  17.                 "ecb": "pushCallbacks.onNotificationAPN" //tell PushPlugin to call onNotificationAPN of global pushCallbacks object
  18.             });
  19.         }
  20.     }
  21.     //subscribe to "deviceready" event with a local function
  22.     document.addEventListener("deviceready", deviceReady, false);
  23. }());

Now if you run the application on your device or in the simulator, you should get something similar to this:

This occurs when the application is not signed with an AppID with enabled push notifications.

In our case, we do need to create a brand new AppID for the application. (For more information, clickhere).

Here, we can add a new AppID with com.icenium.PromotionalApp as a bundle identifier (or you can use whatever bundle identifier you like). We are not done with the AppID yet – we need to enable push notifications for it. Find it in the list and click "Configure". Enable push notifications and click "Configure" for Development Push SSL Certificate.

To set the newly created AppID for the sample application in Graphite, go to Project Properties and modify Application Identifier.

Next, we need to create a certificate signing request (CSR) for a SSL certificate. This will be used to connect our application server to the Apple server. Let's head back to Graphite and create a CSR from Options > General > Certification Management. To generate a certificate signing request (CSR), click the Create button and select Certification Request. Next, save the CSR file on the disk, upload it to the Apple web site, and download the certificate that Apple generates. Back in Graphite, we can now complete the pending request in Options > General > Certification Management by uploading the newly created certificate. The certificate is used to connect to the Apple Push Notification Service (APN).

Now, we will create a specific provision for our application with the new AppID. We will go here and create a new developer provision with our newly created AppID. You might need to hit Refresh a couple of times before the provision becomes active.

Once we have a new developer provision, we need to download it, and in Graphite, import it from Options > Mobile > iOS. 
In Project Properties > iOS, we can set the codesigning identity to our newly created provision. 

The next step is to finally get the device token:

 

In our project, we send this token to the application server, get registered for notifications, and POST an AJAX request to the server with the token. We also implement the onNotificationAPN callback which is called when a push notification is received. 
In the example, the IP address belongs to my local machine. To get your IP, type ipconfig in the command line if you are running Windows, or use ifconfig if you are running Mac OS.

  1. (function() {
  2.     var server = "http://192.168.56.25";
  3.     //make ajax post to the application server to register device
  4.     var sendTokenToServer = function sendTokenToServer(token) {
  5.         $.ajax(server + "/register", {
  6.             type: "post",
  7.             dataType: 'json',
  8.             data: JSON.stringify({ //JSON object with token and the device platform
  9.                 token: token,
  10.                 platform: device.platform
  11.             }),
  12.             success: function(response) {
  13.                 console.log("###Successfully registered device.");
  14.             }
  15.         });
  16.     }
  17.     //the function adds callbacks for PushPlugin
  18.     //the function uses global object "pushCallbacks"
  19.     var addCallback = function addCallback(key, callback) {
  20.         if (window.pushCallbacks === undefined) {
  21.             window.pushCallbacks = {}
  22.         }
  23.         window.pushCallbacks[key] = callback;
  24.     };
  25.     var pushNotification = window.plugins.pushNotification;
  26.     var apnSuccessfulRegistration = function(token) {
  27.         sendTokenToServer(token.toString(16));
  28.         addCallback('onNotificationAPN', onNotificationAPN);
  29.     }
  30.     var apnFailedRegistration = function(error) {
  31.         alert("Error: " + error.toString());
  32.     }
  33.     //the function is a callback when we receive notification from APN
  34.     var onNotificationAPN = function(e) {
  35.         //get promotional text from the application server
  36.         //here we can set a badge manually, or play sounds
  37.         //for more information about PushPlugin, see https://github.com/phonegap-build/PushPlugin
  38.     };
  39.     var deviceReady = function() {
  40.         if (device.platform == "iOS") {
  41.             pushNotification.register(apnSuccessfulRegistration,
  42.             apnFailedRegistration, {
  43.                 "badge": "true",
  44.                 "sound": "true",
  45.                 "alert": "true",
  46.                 "ecb": "pushCallbacks.onNotificationAPN"
  47.             });
  48.         }
  49.     }
  50.     document.addEventListener("deviceready", deviceReady, false);
  51. }());

If everything has worked, in your node.js console, you should see output confirmation for the registered device.

Android

For the Android implementation, we will start by creating a Google API project. You can find the tutorial for that part here. Once we have created our API project, we use its project number to request a token. In our application code, we need to add a function to get the actual promotional text when we receive a push notification. Once we have the promotional text, we will add it to a paragraph on the landing page of our jQuery starting project. Here is how we enhance push.js with the described functionality:

  1. (function() {
  2.     var server = "http://192.168.56.25";
  3.     //add promotion text to the paragraph designed for it
  4.     var addPromotionToDOM = function addPromotionToDOM(promotionText) {
  5.         $("#promotionParagraph").text(promotionText);
  6.     }
  7.     //get promotion text from the application server
  8.     var getPromotionFromServer = function getPromotionFromServer() {
  9.         console.log('### getting promotion text.');
  10.         $.ajax(server + "/getPromotion", {
  11.             type: "post",
  12.             dataType: 'json'
  13.         }).done(function(data) {
  14.             console.log("### got promotion text.");
  15.             addPromotionToDOM(data.text);
  16.         });
  17.     }
  18.     var sendTokenToServer = function sendTokenToServer(token) {
  19.         //make ajax post to the application server to register device
  20.         $.ajax(server + "/register", {
  21.             type: "post",
  22.             dataType: 'json',
  23.             data: JSON.stringify({
  24.                 token: token,
  25.                 platform: device.platform
  26.             }),
  27.             success: function(response) {
  28.                 //log that the device was registered successfully
  29.                 console.log("###Successfully registered device.");
  30.             }
  31.         });
  32.     }
  33.     var addCallback = function addCallback(key, callback) {
  34.         if (window.pushCallbacks === undefined) {
  35.             window.pushCallbacks = {}
  36.         }
  37.         window.pushCallbacks[key] = callback;
  38.     };
  39.     var pushNotification = window.plugins.pushNotification;
  40.     var apnSuccessfulRegistration = function(token) {
  41.         sendTokenToServer(token.toString(16));
  42.         addCallback('onNotificationAPN', onNotificationAPN);
  43.     }
  44.     var apnFailedRegistration = function(error) {
  45.         alert("Error: " + error.toString());
  46.     }
  47.     //the function is a callback when a notification from APN is received
  48.     var onNotificationAPN = function(e) {
  49.         getPromotionFromServer();
  50.     };
  51.     //the function is a callback for all GCM events
  52.     var onNotificationGCM = function onNotificationGCM(e) {
  53.         switch (e.event) {
  54.             case 'registered':
  55.                 if (e.regid.length > 0) {
  56.                     //your GCM push server needs to know the regID before it can push to this device
  57.                     //you can store the regID for later use here
  58.                     console.log('###token received');
  59.                     sendTokenToServer(e.regid);
  60.                 }
  61.                 break;
  62.             case 'message':
  63.                 getPromotionFromServer();
  64.                 break;
  65.             case 'error':
  66.                 alert('GCM error = ' + e.msg);
  67.                 break;
  68.             default:
  69.                 alert('An unknown GCM event has occurred.');
  70.                 break;
  71.         }
  72.     }
  73.     var deviceReady = function() {
  74.         if (device.platform == "iOS") {
  75.             pushNotification.register(apnSuccessfulRegistration,
  76.             apnFailedRegistration, {
  77.                 "badge": "true",
  78.                 "sound": "true",
  79.                 "alert": "true",
  80.                 "ecb": "pushCallbacks.onNotificationAPN"
  81.             });
  82.         } else {
  83.             //register for GCM
  84.             pushNotification.register(
  85.             function(id) {
  86.                 console.log("###Successfully sent request for registering with GCM.");
  87.                 //set GCM notification callback
  88.                 addCallback('onNotificationGCM', onNotificationGCM);
  89.             },
  90.             function(error) {
  91.                 console.log("###Error " + error.toString());
  92.             }, {
  93.                 "senderID": "921067258193",
  94.                 "ecb": "pushCallbacks.onNotificationGCM"
  95.             });
  96.         }
  97.     }
  98.     document.addEventListener("deviceready", deviceReady, false);
  99. }());

On line 106 you need to replace the sender ID with your project number. Now, let's return to our application server for the final touches.

For this to work we also need to set the promotionParagraph ID to the landing paragraph of the application. Here is a snippet from index.html:

  1. <div data-role="page" id="home">
  2.             <div data-role="header">
  3.                 <h1>Hello, World!</h1>
  4.             </div>
  5.             <div data-role="content">
  6.                 <h1>Welcome to Icenium!</h1>
  7.                 <p id="promotionParagraph"> <!-- paragraph contains promotional messages -->
  8.                     Icenium&trade; enables you to build cross-platform device applications regardless of your
  9.                     development platform by combining the convenience of a local development toolset with the
  10.                     power and flexibility of the cloud.
  11.                 </p>
  12.             </div>
  13.             <div class="nav">
  14.                 <ul data-role="listview">
  15.                     <li><a href="#page1" data-transition="slide">UI Interaction Example</a></li>
  16.                     <li><a href="#page2" data-transition="slide">Geolocation Example</a></li>
  17.                 </ul>
  18.             </div>
  19.             <div data-role="footer" data-position="fixed" data-id="oneFooter">
  20.                 <span class="footerText">Built with Icenium&trade;</span>
  21.             </div>
  22.         </div>

Application server

To send our push notifications, we will use two open source modules for Node.js: node-apn and node-gcm. Again, we will add the code separately for iOS and for Android. 
Let's start by installing the two open source modules. Go to the folder where your server js file is. In the command line, type npm install apn and npm install gcm. If everything is OK, you should see two folders in the folder where your server js file is: ./node_modules/apn and ./node_modules/gcm.

Our application server needs to establish an SSL connection with the push notificaion servers of Apple. For this, we will use the private key and certificate that we created earlier for our AppID. We need to create PEM files for the certificate and the private key. You can read more here. Go to Options > General > Certification Management, select the cryptographic identity that we created earlier and export it. For the next part we will need to do some format conversion with OpenSSL.

Creating PEM files from certificate and p12 file

If you're running Windows, download OpenSSL for Windows from here. Note that Microsoft Visual Studio 2008 C++ Distributable is required for OpenSSL under Windows. Mac OS should have OpenSSL out of the box. 
To create the required PEM files, follow the instructions found here.

Now copy the PEM files you created to the folder where your server js file is. In our example, we have named them cert.pem and key.pem. Here's what we need to add to our server code:

NOTE: Make sure that port 2195 is not filtered by your system administrator.

  1. var apns = require('apn');
  2. var options = {
  3.     cert: 'cert.pem',
  4.     /* certificate file path */
  5.     certData: null,
  6.     /* string or buffer containing certificate data; if supplied, uses this instead of certificate file path */
  7.     key: 'key.pem',
  8.     /* key file path */
  9.     keyData: null,
  10.     /* string or buffer containing key data; if supplied, uses this instead of key file path */
  11.     passphrase: null,
  12.     /* passphrase for the key file */
  13.     ca: null,
  14.     /* string or buffer of CA data to use for the TLS connection */
  15.     pfx: null,
  16.     /* file path for private key, certificate, and CA certificates in PFX or PKCS12 format. If supplied, this will be used instead of certificate and key above */
  17.     pfxData: null,
  18.     /* PFX or PKCS12 format data containing the private key, certificate, and CA certificates. If supplied, this will be used instead of loading from disk. */
  19.     gateway: 'gateway.sandbox.push.apple.com', // 'gateway.push.apple.com',/* gateway address */
  20.     port: 2195,
  21.     /* gateway port */
  22.     rejectUnauthorized: true,
  23.     /* value of rejectUnauthorized property to be passed through to tls.connect() */
  24.     enhanced: true,
  25.     /* enable enhanced format */
  26.     errorCallback: undefined,
  27.     /* callback when error occurs function(err,notification) */
  28.     cacheLength: 100,
  29.     /* number of notifications to cache for error purposes */
  30.     autoAdjustCache: true,
  31.     /* whether the cache should grow in response to messages being lost after errors */
  32.     connectionTimeout: 0 /* the duration (in milliseconds) the socket should stay alive with no activity. 0 = Disabled. */
  33. };
  34. var apnsConnection = new apns.Connection(options);
  35. apnsConnection.on('error', function(error) {
  36.     console.log('Error with APN ' + error);
  37. });
  38. apnsConnection.on('transmitted', function(notification) {
  39.     console.log('Notification sent to APN ' + notification.toString());
  40. });
  41. apnsConnection.on('connected', function() {
  42.     console.log('Connected to APN.');
  43. });
  44. apnsConnection.on('disconnected', function() {
  45.     console.log('Disconnected from APN.');
  46. });
  47. apnsConnection.on('transmissionError', function(errorCode, notification) {
  48.     console.log("Transmision error with APN. Error code " + errorCode + " notification: " + notification.toString());
  49. });

Finally, it's time for some push notifications. Let's add a function that lists all iOS devices and sends them a generic push notification that a new promotion is available.

  1. function notifyDevices() {
  2.         var textMessage = "New promotion available.";
  3.         for (var i = allDevices.length - 1; i >= 0; i--) {
  4.                 if (allDevices[i].platform == "iOS") {
  5.                         var token = allDevices[i].token;
  6.                         var device = new apns.Device(token);
  7.                         var note = new apns.Notification();
  8.                         note.expiry = Math.floor(Date.now() / 1000) + 3600*24; //set to expire 24 hours after the notification is sent
  9.                         note.badge = 1;
  10.                         note.alert = textMessage;
  11.                         note.device = device;
  12.                         apnsConnection.sendNotification(note);
  13.                 }
  14.         };
  15. }

We need to call this function when we receive new promotional text.

  1. function setPromotion(request, response) {
  2.   request.on('data', function(data) {
  3.                 promotionText = decodeURI(data.slice(data.indexOf("=") + 1));
  4.                 promotionText = promotionText.replace(/\+/g, ' ');
  5.                 notifyDevices(); //ping all devices that a new promotion is available
  6.         })
  7.         response.writeHeader(200, { "Content-Type": "text/html"} );
  8.         response.write("Successfully added to queue.");
  9.         response.end();
  10. }

Now, iOS devices should display the promotional text in the landing page paragraph. We just need to add the code for Android devices to our project, and we are done.

To send messages to GCM (Google Cloud Messaging), we use the API key for the Google API project we created earlier. You can find your own API key here, in the API Access tab. The final touches to our server code look like this:

  1. var http = require('http');
  2. var url = require('url');
  3. var fs = require('fs');
  4. //GCM implementation
  5. var GCM = require('gcm').GCM;
  6. var apiKey = 'AIzaSyBjXSsrENe404ICODKEMtCdyYuOsuqLzbU'; //replace with the API key for your Google API project
  7. var gcm = new GCM(apiKey);
  8. //
  9. var apns = require('apn');

The only thing left is to enumerate all Android tokens and send push notifications to them. To do that, we need to modify the notifyDevices() function.

  1. function notifyDevices() {
  2.         var allAndroidTokens = [];
  3.         var textMessage = "New promotion available.";
  4.         for (var i = allDevices.length - 1; i >= 0; i--) {
  5.                 if (allDevices[i].platform == "iOS") {
  6.                         var token = allDevices[i].token;
  7.                         var device = new apns.Device(token);
  8.                         var note = new apns.Notification();
  9.                         note.expiry = Math.floor(Date.now() / 1000) + 3600*24; //set to expire 24 hours after the notification is sent
  10.                         note.badge = 1;
  11.                         note.alert = textMessage;
  12.                         note.device = device;
  13.                         apnsConnection.sendNotification(note);
  14.                 } else {
  15.                         allAndroidTokens.push(allDevices[i].token); //for Android devices, remember the token
  16.                 }
  17.         };
  18.         if (allAndroidTokens.length == 0)
  19.                 return;
  20.         var message = {
  21.             'registration_id' : allAndroidTokens,
  22.             'data.message' :  textMessage,
  23.             'data.msgcnt' : 0,
  24.         };
  25.         gcm.send(message, function(err, messageId){ //send message to all registered Android devices
  26.             if (err) {
  27.                 console.log("Something has gone wrong with GCM send!");
  28.             } else {
  29.                 console.log("Sent with message ID: " + messageId + " on GCM.");
  30.             }
  31.         });
  32. }

Conclusion

It was a long road but if you are reading this you are ready to create some amazing apps using push notifications. Keep in mind that the implementation here is very basic and you can do a lot more to make it production ready. For example, you can use the APN feedback service to keep track of undelivered messages and identify unreachable devices. A few more ideas: fetch promotions when app starts, unsubscribe from promotions, and so on. 

Sample Code

If you'd like to explore further, feel free to download the promotion app and server.js module code. 

Evgeni Petrov

About the Author
 is one of the mobile guys at Icenium. He has been involved in numerous mobile project throughout his career. He's passionate about UX and Developer Tools. When he's not looking at the computer monitor, he loves to play drum solos. Evgeni works as a Software Developer @ Telerik.


Related Posts

Comments

Comments are disabled in preview mode.