Push Notification in Intel XDK using Push Plugin

In this tutorial I will show how to integrate push notification in a Cordova Hybrid apps. Intel XDK legacy apps use pushMobi webservice to integrate push notifications but in cordova hydrid apps you have to use third party plugins.

Include Push Plugin

In this tutorial we will use third party Push Plugin to integrate push notification in Intel XDK cordova hydrid APP.

Android Prerequisite

For android you need to create a Google Developers Console project and retrieve project ID and API key

Understanding Push Notification Mechanism

Push Notification is useful when app is in background or lock state and you want to notify user about something important. You need to send the messages from your server to mobile vendor server’s and they will deliver the message to the respective phones.

When app is in background a tile is usually displayed when a new notification is received. When user clicks on the tile the app is switched to foreground state and a callback is fired by passing the message as parameter.

If app is in foreground then just a callback is fired when a new notification is received.

Registering User

Some apps require user to login to use it. For example: Gmail, Facebook etc apps require you to create or login to account. Some apps like Flappy bird, blog etc doesn’t require user to login.

Apps that require login actually sends different push notifications to different users. But the apps that don’t require login send same push notifications to all users.

If your app falls into login required category than When a user installs your app, your app needs to register the user to identify it uniquely. This will allow you to send notifications to specific users identified uniquely. Your app will get a unique token to identify the device in which app is installed. You need to send the token along with user credentials to your server so that you know to which device you need to send notification to for a particular user.

If your app falls into non-login category than also you need to register the user but in this case you can just send the unique token to your server. And then send push notification to all tokens.

Here is the code on how to register and retrieve the unique token for Android and iOS

var tokenID ="";

document.addEventListener("deviceready",function(){//Unregister the previous token because it might have become invalid. Unregister everytime app is started. window.plugins.pushNotification.unregister(successHandler, errorHandler);

if(intel.xdk.device.platform=="Android"){//register the user and get token window.plugins.pushNotification.register( successHandler, errorHandler,{//senderID is the project ID"senderID":"",//callback function that is executed when phone recieves a notification for this app"ecb":"onNotification"});}elseif(intel.xdk.device.platform=="iOS"){//register the user and get token window.plugins.pushNotification.register( tokenHandler, errorHandler,{//allow application to change badge number"badge":"true",//allow application to play notification sound"sound":"true",//register callback"alert":"true",//callback function name"ecb":"onNotificationAPN"});}},false);

//App given permission to receive and display push messages in iOSfunction tokenHandler (result){// Your iOS push server needs to know the token before it can push to this device// here is where you might want to send the token to your server along with user credentials. alert('device token = '+ result); tokenID = result;}

//fired when token is generated, message is received or an error occured.function onNotification(e){switch( e.event){//app is registered to receive notificationcase'registered':if(e.regid.length>0){// Your Android push server needs to know the token before it can push to this device// here is where you might want to send the token to your server along with user credentials. alert('registration id = '+e.regid); tokenID = e.regid;}break;

case'message'://Do something with the push message. This function is fired when push message is received or if user clicks on the tile. alert('message = '+e.message+' msgcnt = '+e.msgcnt);break;

case'error': alert('GCM error = '+e.msg);break;

default: alert('An unknown GCM event has occurred');break;}}

//callback fired when notification received in iOSfunction onNotificationAPN (event){if( event.alert){//do something with the push message. This function is fired when push message is received or if user clicks on the tile. alert(event.alert);}

Sending Push Notification from PHP Server to Apple Push Servers

Here is the PHP code snippet to send push notification from your own server to apple servers so that apple can deliver it to the app.

<?php

$passphrase="";//enter passphrase that you created while generating .pem file$message="Sample Notification";//notification message$token="";//enter the token received by the app to uniquely identify device on which app is installed.

$payload='{"aps":{"alert":"'.$message.'","sound":"default","badge":"1"}}';//set message, sound and badge number for the app callback to receive$result='Start'.'<br />';$ctx=stream_context_create();stream_context_set_option($ctx,'ssl','local_cert','ck.pem');//last parameter is the name of the .pem file.stream_context_set_option($ctx,'ssl','passphrase',$passphrase);$fp=stream_socket_client('ssl://gateway.push.apple.com:2195',$err,$errstr,60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT,$ctx);if(!$fp){exit("Failed to connect: $err$errstr".'<br />');}else{echo'Apple service is online. '.'<br />';}

Hi Narayan Prusty, thank you for this tutorial is useful i run it successfully but i have one tiny problem when my phone receive first notification is OK but if there is another notification comes, it replaces the previous one.

Hi Code is not working for me showing the error “Warning: the Cordova CLI 3.3 and 3.5 build options have been deprecated and will be removed before the end of 2015 (or sooner). Applications built with these versions of the Cordova CLI are no longer or will soon be no longer accepted by either the Google Play or the Apple Store.”

One thing I’m struggling to understand. At the moment there’s a button to press to receive a message. from the server. Obviously we want this to happen automatically. Should we create a function which checks every hour?? Am I missing the point??

There was recent update for intel xdk (2496 )that have issue with 3rd party plugins. Until they solve it. I’m afraid it wont work. Also plugin is deprecated now so you may move on to new version that support CLi 5.x+

Hi, I’ve tried to follow your tutorial in my XDK app and also tried to run your XDK from the imported project, but I always get the error “cannot read property ‘push notification’ of undefined”, as the plugin was not loaded. Any advice? Thanks and regards.

HI HO tried PROJECT BUT I CAN NOT GET ME THE SECOND PUSCH COIN ID DOES NOT WARRANT from the app TRACKS PHP THEN THE MESSAGE IS NOT SENT EC SOMEONE WHO CAN post A SOURCE THAT THIS IS NOT THAT I MAKE SURE IT WORKS THANKS

Hi, Thanks for the tutorial. I did the same as you said. BUt where do I include the pem file or have a separate push certificate in the cordova build? There are only two options one to upload a provisioning profile in the projects section and 1 certificate section in the build tab

PEM file should be on your server, the server that contact apple server when sending push message. The other certificate you are including in build section of XDK. It wont let you build without it. Of course you also need Apple Developer Certificate that cost you $100 per year and your personal developer account on apple servers where you create all needed certificates.

To everyone who doesnt seem to make this work. I download code uploaded by this tutorial author and make some changes. First, do everything what he say on the beginnig of this course with registering with Google Cloud. Then you need to update code with your own ProjectID. Next, make sure you have running own server. I used XAMPP on Windows and run android.php from author’s git repository. Changes API key to my from Google Cloud and in app change AJAX request to IP of my local machine. And one more thing. In app I had to change line

intel.xdk.device.platform

to

device.platform

Please stop sending rude, racial abusive messages to this guy. He knows what he is doing , just maybe isnt great with describing all details required. Its also worth to read PushPlugin documentation. It includes sample code to make all run with Intel XDK

To all who using XDK. Move to native cordova calls with ‘navigator’. Once I did that suddenly my device started to vibrate when I told it to, native popup messages worked and many many more. intel.xdk namespace works…. but only on emulators. On real device when you deploy app it just doesnt.

Program doesn’t work for me :/ I copied all files and have PushPlugin installed. When i turn the app on my device there is altert “result OK” but when i click in button “test push notification” nothing happens.

The alert comes from code for unregistering the device. Google claims to not do that very often, only if you have to. And also change ‘intel.xdk.device.platform’ in your code to ‘device.platform’. Try again

Thanks for a great article on this. I wonder if you can assist. I’m testing this on an android device and I get “error = Class not found” which comes from the errorHandler when trying to register the device. I’ve banged my head against the wall and am just not getting past this error. I suspect that the issue is that adding Push Plugin is not happening sucessfully. When I inspect the apk file, I don’t see any jar files. I tried adding it as suggested and by downloading the plugin and using the “Import local plugin” option on XDK. I’d appreciate your assistance.

For all people that doesn’t work the demo uploaded by Narayan, must verify if they have the requiered plugins selected at the ‘Cordova 3.X Hybrid Mobile App Settings in the Projects section’, must checked in included plugins ‘Device’ in Standard Cordova Plugins section and in the Featured & Custom Cordova Plugins section.

I was passing an hash/dictionary as this data = {‘the_message': ‘You have x new friends’, ‘sender':’andre’}, so i have changed to data = {‘message': ‘You have x new friends’, ‘sender':’andre’} and the notification now apears on the notification tray.

Its not possible to host the app on server for iOS because to test you have to make adhoc build and the device UUID’s are predefined while creating the app. So pem file and certificates are different for all devices.

But for android its possible to upload to server. Give me couple of days I will upload it on my server for testing. Remember its only for android.

Hi Master, I just beginners in mobile development. Sorry if I’m slow to understand. Would you like to share your demo project (.xdk) on github so I can try it. It will further enhance the value of your tutorial.

Hi Code is not working for me showing the error “Warning: the Cordova CLI 3.3 and 3.5 build options have been deprecated and will be removed before the end of 2015 (or sooner). Applications built with these versions of the Cordova CLI are no longer or will soon be no longer accepted by either the Google Play or the Apple Store.”

every time I include push plugin is give me error , please help me out

To all those who are having a hard time understanding why TOKEN is EMPTY.

This is to clarify that the tutorial is perfectly fine. You are NOT getting the whole concept of how GCM works.

THERE ARE THREE PARTS HERE INVOLVED

THE PHP SERVER THE PHONE APP THE GCM SERVICE

STEP 1 – PHONE APP CONNECTS TO GCM SERVICE AND GETS TOKEN BACK. NOTE PHONE APP HAS TO HAVE VALID PROJECT ID IN IT. THIS IS WHY THAT TOKEN Variable is empty … it gets POPULATED by the GCM STEP 2 – SEND the TOKEN TO the SERVER STEP 3 – SERVER can now CONNECT TO GCM with the TOKEN and GCM knows WHERE to send the message thanks to the token…… STEP 4 – STOP OFFENDING THE TUTOR! GO OFFEND INTEL INSTEAD THEY GOT NO DOCUMENTATION ON XDK and THIS GUY IS DOING YOU a BLOODY FAVOUR.

To create code blocks or other preformatted text, indent by four spaces:

This will be displayed in a monospaced font. The first four
spaces will be stripped off, but all other whitespace
will be preserved.
Markdown is turned off in code blocks:
[This is not a link](http://example.com)