Push Notification Phonegap Plugin for Android and iOS – Part 1

Push notification is describes a style of Internet-based communication where the request for a given transaction is initiated by the publisher or central server. It is contrasted with pull, where the request for the transmission of information is initiated by the receiver or client (Wikipedia).

There are two types of push notification service that mostly popular among the others are android and iOS. I’m not sure about blackberry and windows mobile because currently doing only for iOS and android platform.

Push notification for iOS called APNs stands for Apple Push Notification Service. For android called GCM stands for Google Cloud Messaging. You can find more details about both of these services at their official site.

APNs

APNs

GCM

GCM

Last month I already attend worklight training located at Plaza IBM, One Utama organised by IBM. I already post an article about this training details here.

http://blog.revivalx.com/2014/02/18/ibm-worklight-training-day-2/

Besides that, you can find more details about APNs and GCM from third party links.

APNs

  1. http://www.raywenderlich.com/32960/apple-push-notification-services-in-ios-6-tutorial-part-1
  2. http://devgirl.org/2012/10/19/tutorial-apple-push-notifications-with-phonegap-part-1/

GCM

  1. http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/

Ok, enough chit chat. Now, I want to share with you how to do push notification phonegap plugin for android platform. First, you need to create cordova project. Make sure you have eclipse Juno and Xcode (for mac users).

cordova create project

cordova create project

Open up your config.xml in your project then edit project id and name.

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.revivalx.PushNotification" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>PushNotification</name>
    <description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>
    <author email="dev@cordova.apache.org" href="http://cordova.io">
        Apache Cordova Team
    </author>
    <content src="index.html" />
    <access origin="*" />
</widget>

Go to your project directory then add these two platforms into your cordova project, iOS and android.

Run this command in your terminal.

cordova platform add android
cordova platform add ios
android

android

iOS

iOS

Create a new project in eclipse.

eclipse new project

eclipse new project 1

eclipse new project 2

eclipse new project 2

eclipse new project 3

eclipse new project 3

Make sure your project hierarchy look like this one.

Download this phonegap plugin and install into your cordova project.

https://github.com/phonegap-build/PushPlugin

https://github.com/apache/cordova-plugin-console

Run this command to install this plugin into your project.

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

cordova plugin

To make your push notifications works, you need to register your app first in google cloud (android) and apple developer (iOS).  For android part, you need project id for push notification recognise your device. Otherwise, it won’t work. You can refer this tutorial how to register your app.

iOS: http://www.raywenderlich.com/32960/apple-push-notification-services-in-ios-6-tutorial-part-1

Android: http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/

Below are websites that you need to register your app for push notification.

Google Cloud: https://cloud.google.com

Apple Developer: https://developer.apple.com/

After you finish registered your app, go back to your eclipse and insert this script into your index.html .

https://github.com/phonegap-build/PushPlugin/blob/master/www/PushNotification.js

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Hello World</title>
<script src="js/PushNotification.js"></script>
<script>
var pushNotification;

function onDeviceReady() {
pushNotification = window.plugins.pushNotification;
if (device.platform == 'android' || device.platform == 'Android') {
console.log("registering android");
pushNotification.register(successHandler, errorHandler, {
"senderID": "xxxxxxxxxxx",
"ecb": "onNotificationGCM"
}); // required!
} else {
console.log("registering iOS");
pushNotification.register(tokenHandler, errorHandler, {
"badge": "true",
"sound": "true",
"alert": "true",
"ecb": "onNotificationAPN"
}); // required!
}
}
// handle APNS notifications for iOS

function onNotificationAPN(e) {
if (e.alert) {
navigator.notification.alert(e.alert);
}
if (e.sound) {
var snd = new Media(e.sound);
snd.play();
}
if (e.badge) {
pushNotification.setApplicationIconBadgeNumber(successHandler, e.badge);
}
}
// handle GCM notifications for Android

function onNotificationGCM(e) {
navigator.notification.alert(e.event);
switch (e.event) {
case 'registered':
if (e.regid.length > 0) {
navigator.notification.alert(e.regid);
// Your GCM push server needs to know the regID before it can push to this device
// here is where you might want to send it the regID for later use.
console.log("regID = " + e.regid);
}
break;
case 'message':
// if this flag is set, this notification happened while we were in the foreground.
// you might want to play a sound to get the user's attention, throw up a dialog, etc.
if (e.foreground) {
navigator.notification.alert('--INLINE NOTIFICATION--');
// if the notification contains a soundname, play it.
var my_media = new Media("/android_asset/www/" + e.soundname);
my_media.play();
} else { // otherwise we were launched because the user touched a notification in the notification tray.
if (e.coldstart) navigator.notification.alert('--COLDSTART NOTIFICATION--');
else navigator.notification.alert('--BACKGROUND NOTIFICATION--');
}
navigator.notification.alert(e.payload.message);
navigator.notification.alert('MESSAGE -> MSGCNT: ' + e.payload.msgcnt);
break;
case 'error':
navigator.notification.alert('ERROR -> MSG:' + e.msg);
break;
default:
navigator.notification.alert('EVENT -> Unknown, an event was received and we do not know what it is');
break;
}
}

function tokenHandler(result) {
navigator.notification.alert(result, null, 'Alert', 'OK');
sessionStorage.setItem("deviceId", result);
sessionStorage.setItem("notificationServer", "APNS");
// Your iOS push server needs to know the token before it can push to this device
// here is where you might want to send it the token for later use.
}

function successHandler(result) {
navigator.notification.alert(result, null, 'Alert', 'OK');
sessionStorage.setItem("deviceId", result);
sessionStorage.setItem("notificationServer", "GCM");
}

function errorHandler(error) {
navigator.notification.alert(error, null, 'Alert', 'OK');
}
document.addEventListener('deviceready', onDeviceReady, true);
</script>
</head>
<body>
<div class="app">
<h1>Apache Cordova</h1>
<div id="deviceready" class="blink">
<p class="event listening">Connecting to Device</p>
<p class="event received">Device is Ready</p>
</div>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>

Then build your project. Run these command in your terminal.

cordova build ios
cordova build android
cordova build ios

cordova build ios

cordova build android

cordova build android

I will continue on the second part about how to test your push notification for android and ios. Don’t hesitate to contact me if you had problem about this.