Tutorial: Implement Push Notifications in your PhoneGap Application
In this tutorial you will implement push notifications in your PhoneGap application. You will learn the following:
- An overview of the push notification handling process
- How to use the PushPlugin supported by PhoneGap Build
- An overview of the PushPlugin APIs
- How to register your application to receive push notifications
- How to use a simple node service to send a push notification to your registered device
- Differences between Android and iOS for handling push notifications
Overview
Android devices receive push notifications through the Google Cloud Messaging (GCM) service, whereas iOS devices receive them from the Apple Push Notifications (APN) Service. Though there are differences in the two services in terms of the size of the payload that can be sent, certificates required etc, both act as a store and forward type of service where they receive a message from a 3rd party, identify the recipient and pass it along. Upon receipt, your application that has registered to receive them can examine the returned contents and act accordingly. The way the notifications are received (by sound, alert etc) is a combination of the options set in the application code upon registration as well as the user’s device settings for notifications.
Getting Started
There is an official plugin called PushPlugin available to use for push notifications support and it’s supported by PhoneGap Build. This is the plugin used in the tutorial. The source code for a working project for PhoneGap Build (PhoneGap version prior to 3.0) can be found on my github account here. If you’re working with PhoneGap version 3.0 or greater, a complete working project for that version can be found here.
This tutorial does not go into depth about creating accounts on Google Cloud Messaging or the details behind setting up your application with the Apple Developer Portal but see the following articles on those topics.
I will be focusing mainly on Android and the Google Cloud Messaging service in this tutorial. However, see these two posts below on using push notifications for iOS:
Android Pre-requisites
- Google Cloud Messaging Project ID
- Google Cloud Messaging API Key for above Project ID (need for server)
iOS Pre-requisites
- App ID configured for Push Notifications on Apple Developer Portal
- SSL Certificate and private key (need for server)
Part 1: Configure your app to use the PushPlugin
In this part we’re going to add support for the PushPlugin to our application.
***Plugin Installation with the PhoneGap CLI (Command Line Interface)
- Create a basic PhoneGap project
$ phonegap create PushNotificationSample --id "com.pushapp" --name "PushNotificationApp"
- cd into the newly created project folder
$ cd PushNotificationSample
- Build the application for Android (also adds it as a platform under the /platforms folder)
$ phonegap local build android
- Install the PushPlugin from its github location via the PhoneGap CLI:
$ phonegap local plugin add https://github.com/phonegap-build/PushPlugin
- Locate the PushNotification.js file that was installed into your project-root/plugins folder. This file must be copied into your project-root/www folder and referenced from the index.html currently. The file should exist under in a location such as mine:
../PushNotificationSample/plugins/com.phonegap.plugins.PushPlugin/www/PushNotification.js
- Add the following script line to your index.html to reference the PushNotification.js.
<script type="text/javascript" src="PushNotification.js"></script>
Now you’re ready to start adding code and can skip to Part 2!
***Plugin Installation for PhoneGap Build
For PhoneGap Build you’ll need to refer to the plugin in the www/config.xml file in the project root and specify the script tag for the PushNotifications.js file and PhoneGap Build will inject it for us at build time. These steps are shown below:
- Add the following script line to your index.html to reference the PushNotification plugin.
<script type="text/javascript" src="PushNotification.js"></script>
- Add the following line to the www/config.xml file so PhoneGap Build will know to inject the Push Plugin code:
<gap:plugin name="com.adobe.plugins.pushplugin" />
Part 2: Register the application with the Google Cloud Messaging service
In this step we will register our application with the Google Cloud Messaging service to receive push notifications.
Start by creating an account and project with the GCM service here. Once your project is created, it will be assigned a project id. You can see that id in the GCM console but it’s also appended to the URL such as this: https://code.google.com/apis/console/#project:824841663931. Make note of it as you will need it for the registration call.
- Open your base application in your editor and navigate to the www/js/index.js file. In the receivedEvent function, add the following code to get a reference to the push notification plugin object and call the register function. You will need to pass in a success and error callback function and then a couple of parameters including the project id you were assigned when you set up your project with Google Cloud Messaging as the senderID and a callback function for any messages received from GCM as the ecb parameter:
var pushNotification = window.plugins.pushNotification; pushNotification.register(app.successHandler, app.errorHandler,{"senderID":"824841663931","ecb":"app.onNotificationGCM"});
- Start with adding the successHandler which will be called when the registration is successful. The result will contain the registration token and we are displaying it in an alert:
// result contains any message sent from the plugin call successHandler: function(result) { alert('Callback Success! Result = '+result) },
- Next add the errorHandler to be called if an error is returned from the registration request. In this handler we’ll simply display an alert showing the error received:
errorHandler:function(error) { alert(error); },
-
And finally add the callback function to be called when messages are received from GCM to the end of your index.js file before the closing bracket. In my case I’ve named it onNotificationGCM as we may go back and add support for iOS push notifications to the same application and would need a different callback in that case. The function checks for the event received and handles simply displays an alert showing the contents.
onNotificationGCM: function(e) { switch( e.event ) { case 'registered': if ( e.regid.length > 0 ) { console.log("Regid " + e.regid); alert('registration id = '+e.regid); } break; case 'message': // this is the actual push notification. its format depends on the data model from the push server 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; } }
Run your application
You have a few options you can choose to run your application…
- Run locally with CLI
You can run your application on your local device using the PhoneGap CLI with the following command from your terminal window from somewhere inside your project root:
$ phonegap local run android
- Run remotely with CLI
You can send your application to be built on PhoneGap Build and receive the QR code on the command line to run it from by using the following:
$ phonegap remote run android
-
Run with PhoneGap Build
Log in to PhoneGap Build and upload your project zip to PhoneGap Build or specify its’ git location and build through the web interface. Scan the QR code or download the resulting package to your device.
When you run the application you should see a call made to register your android device and a token received in an alert such as shown below:
So now our application is ready to receive push notifications from the Google Cloud Messaging service. We can test out sending a message using some simple JavaScript with nodejs. There’s a library called node-gcm that we can use to send push notifications to GCM. We’ll just need the token or registration id that was returned from our call to register with GCM, as well as a server API key from GCM that’s associated with our project. You create this key in the GCM console for your project id under the API Access menu. Click Create new Server key…
- Install the node-gcm module. This library handles the communication with the Google Cloud Messaging server and gives you helpful classes to make it easy to send a message.
- Go to your GCM console and locate the Server API key (click the API Access link in the menu on the left to locate they keys). If you haven’t created one already you will need to do so now.
- Get the registration id returned to our application from the console. I like to use the Android adb tool so I can run logcat to watch the console while my application is running. Assuming you have the android-sdk tools and platform-tools set on your environment path you can simply run
adb logcat
from the command line to show your device log. - Open your editor and create a file called notify.js and paste in the following, replacing the Sender key and device registration id with yours.
var gcm = require('node-gcm'); var message = new gcm.Message(); //API Server Key var sender = new gcm.Sender('AIzaSyCDx8v9R0fMsAsjoAffF-P3FCFWXlvwLhg'); var registrationIds = []; // Value the payload data to send... message.addData('message',"\u270C Peace, Love \u2764 and PhoneGap \u2706!"); message.addData('title','Push Notification Sample' ); message.addData('msgcnt','3'); // Shows up in the notification in the status bar message.addData('soundname','beep.wav'); //Sound to play upon notification receipt - put in the www folder in app //message.collapseKey = 'demo'; //message.delayWhileIdle = true; //Default is false message.timeToLive = 3000;// Duration in seconds to hold in GCM and retry before timing out. Default 4 weeks (2,419,200 seconds) if not specified. // At least one reg id required registrationIds.push('APA91bwu-47V0L7xB55zoVd47zOJahUgBFFuxDiUBjLAUdpuWwEcLd3FvbcNTPKTSnDZwjN384qTyfWW2KAJJW7ArZ-QVPExnxWK91Pc-uTzFdFaJ3URK470WmTl5R1zL0Vloru1B-AfHO6QFFg47O4Cnv6yBOWEFcvZlHDBY8YaDc4UeKUe7ao'); /** * Parameters: message-literal, registrationIds-array, No. of retries, callback-function */ sender.send(message, registrationIds, 4, function (result) { console.log(result); });
node notify.js
You should hear the notification and see it in your status bar like this on your Android device (varies by device model):

When clicked on, the application should open and you should see this alert popup showing the message data:
Other Things to Note…
- You can set the badge number from the PushPlugin API via:
pushNotification.setApplicationIconBadgeNumber(this.successHandler, 0);
- You can specify a custom sound to play by including the sound file in your www folder and referring to it from the server side.
Differences between Android and iOS
- Android payload size is 4k whereas iOS payload size is 256 bytes
- iOS requires extra set up from the Apple Developer Portal to authorize the app id for push notifications, as well as be signed with a unique SSL certificate that the server can verify against.
- GCM will always return a message indicating if a device id has changed or is invalid, but with Apple you need to periodically ping their feedback server to find out which device tokens have become invalid.
- You can specify a timeToLive parameter for Android of 0 seconds to 4 weeks on the life of your notification. Apple does not specify any given time period.
- For Android you can specify a collapseKey which will allow you to save up messages and only the last one will be delivered. On iOS if you send multiple notifications to a device that is offline, only the last message will get delivered.
Summary
Now that you know how you can receive push notifications, the next step would be to save the registration id’s or device tokens from all of the devices that are running your application so you can access them from the server-side when you need to send a notification for your application. You would also of course add and any specific handling code needed when certain notifications are received.
Filed in: Android • Cordova • PhoneGap • Push Notifications
About the Author (Author Profile)
Comments (150)
Trackback URL | Comments RSS Feed
Sites That Link to this Post
- Tutorial: Implement push notifications in your PhoneGap application | July 19, 2013
- mobile apps - mobile app development | July 20, 2013
- Tutorial: Implement Push Notifications in your PhoneGap Application | TechnoVeille | July 26, 2013
- Cannot find module 'node-gcm'CopyQuery CopyQuery | Question & Answer Tool for your Technical Queries,CopyQuery, ejjuit, query, copyquery, copyquery.com, android doubt, ios question, sql query, sqlite query, nodejsquery, dns query, update que | November 26, 2013
- Cannot find module 'node-gcm' - QueryPost.com | November 26, 2013
- Register a device on GCM every time it opens is the right approach? | Ask Experts | January 4, 2014
Hi, thank you for this great tutorial! I have been reading through all of the Phonegap docs and trying to implement the push notification for the past 3 days. I was able to get it working with the notify.js file! I wanted to ask if you could possible also explain step by step how to use a 3rd party pushplugin, such as Apigee PushNotification? I am just unable to understand how to connect the dots when it comes to editing the plugin.xml file, the config.xml file, and where to place all of the jar files. It has been a frustrating weekend.
http://apigee.com/docs/usergrid/content/tutorial-push-notifications
https://github.com/apigee/appservices-phonegap-push-plugin
Thank you again for the fine details:)
PG
Thank you for posted this tutorial.
I have an question, after downloaded your source code of the completed project. I did change the senderID to mine. Then I uploaded the app thru PhoneGap and downloaded it in my android device. When I launch the app, it shown Connecting to device.
Can you tell me what I still need to change in your source code?
Thank You,
Jasper
Sorry, after posted this question, my problem solved in miracle..Anyways Thanks!
Hi Jasper,
Can you tell me how you were able to get it to work? I’m having the same problem.
Hi Holly
Thank you for your tutorials. They have helped a lot. I would like some help though in some sample code of how you would send the registration id for Android and IOS to your local push server. I assume you would do this in index.js in the case statement, but I have been unable to get it to send it so far and I am new to this process.
Thanks
Brandon
Hi Brandon, check out this post I wrote previously for some more information on that -> http://devgirl.org/2012/10/19/tutorial-apple-push-notifications-with-phonegap-part-1/. There’s also a project that goes along with it that has some simple code to talk to the server and pass the reg id… Hope that helps :)! Holly
Nice write up, thanks!
Would be nice if there was more info on using the push plugin without pg build.
Hi, I agree with Brandon, it would be great to see in what way we could send the sender id to our own server. I was able to send a push notification using PHP instead of node-gcm but now just have to figure out how to send the sender id to my server from the android device.
Sending push using PHP
http://distriqt.com/post/1273
Regards,
PG
Hi PG, check out this post I wrote previously for some more information on that -> http://devgirl.org/2012/10/19/tutorial-apple-push-notifications-with-phonegap-part-1/ and look at the project that goes along with it. It that has some simple code to talk to the server and pass the reg id… The server uses node but you could do something similar with PHP… Hope that helps :)! Holly
Hi, I’ve tried out your code but i’m having some issues.
When i try to push from my server i get the following response, which i think is a succesfull push:
“{“multicast_id”:4652607928164468840,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{“message_id”:”0:1375262603215512%760e4cd6f9fd7ecd”}]}”
But the message is not delivered to my device. Also, i am not recieving the alerts from the successHandler nor the errorHandler functions. I am, however, recieving the registration alert along with the device id, but i have a suspicion it’s not really registering because the succesHandler function is not alerting.
Am i doing something wrong, or is this a common issue?
Regards, Ben
Never mind! I found out that my company network’s firewall was blocking my requests…
Oh good, I’m glad you figured it out and let me know for others as well, thanks :)!
Hi Holly,
I have another quick question:
How can I retrieve additional key/value pairs from the $data array?
This link states that there’s no limit to these pairs except for the overall payload of the notification:
http://developer.android.com/google/gcm/gcm.html
I have successfully sent a notification with an extra key+value like this:
$fields = array(
‘registration_ids’ => $registrationIDs,
‘data’ => array( “message” => $message, “test”=>’testvalue’ )
);
However, when I try to retrieve this data inside of the app the e.test is undefined:
alert(‘test = ‘+e.test);
Is this possible with this push plug-in? Because i want to navigate to a certain page in the app when opening the notification.
Thanks!
Ben
Again, never mind!
I logged the entire event object and found out that the extra key/value pairs are inside of the payload object. So, for anyone wondering:
The message text can be retrieved with: e.message
All other key/value pairs can be retrieved with: e.payload.key
Thanks!
Ben,
You sir are the best, thank you for sharing your findings! Much appreciated.
Thanks!
PG
ben,
Thank you so much for sharing this finding. I dont know why i couldnt find it, but I was frustated a lot to get this. Thanks a lot.
Hi Ben, thanks for that info,
Is that for iOS(APNS) too???
Awesome tutorial. I was wondering if you know how to format the notification in a different way. I have seen notification on my phone before that had extra images and different color text. Any idea how this is done.
Also my app icon shows up really small in the notification. Any clue how to remedy that?
Thanks
I am not getting any registering key.It is also not showing any error.Last line i can see in logcat is
Registering app com.example.ridetaxi of senders 824841663931.
Thanks for tutorial, I installed this plugin with tutorial in your video-instruction. That was really helpfull! But when I click on my notification it shows desctop, not my app :C How can i resolve that?
Hi Holly
Thanks for your sharing. I am new to android developing. I followed every detail you mentioned in your tutorial and when I run my application, the messaging is like:
PushNotification Plugin Demo
deviceready event received
registering android
error: Class not found
I am sure that configurations in config.xml and manifest.xml are correct. So if there is any extra hint for me if will appreciated.
Thanks!
Wade
hi Wade,
were u able to figure out the problem and get it running ? I am also running into same issue…
I know this is a bit late, but I was able to fix the “Class not found” error by rebuilding the app without Hydration from inside of PhoneGap Build.
Any idea what’s going on with the PushPlugin repo? It’s totally broken with Cordova 3.0 and the PhoneGap team doesn’t seem to be touching it. There are multiple outstanding pull requests to fix blocking issues. Would be great if one of the Adobe maintainers could check it out.
Hi Jason, the last version I had tried it with was 2.9, but in the pull requests it appears they updated it to work with 3.0. What kind of blocking issues? Did you try reporting it anywhere? You can report issues on it here: https://github.com/phonegap-build/PushPlugin/issues. You should take a look at this one in particular as well: https://github.com/phonegap-build/PushPlugin/issues/37… Thanks! Holly
Holly, thanks for the response. I’m the person who submitted the pull request fixing the issue that you reference (https://github.com/phonegap-build/PushPlugin/pull/39). However, none of the repo maintainers seem to be monitoring the issues list or accepting any of the pull requests.
Oh I see, ok Jason, let me see what I can find out… So is the plugin not working for you at all with 3.0?
The details are all in the pull request but:
-Old iOS method signatures were deprecated in PhoneGap 2.7 and removed in 3.0. This causes the iOS plugin to fail – completely. Android class naming change as well, which causes that plugin to fail.
-Cordova CLI changed iOS projects to ARC format, and the plugin does not work with ARC.
-Installation of the plugin fails because of a breaking change in the config xml format.
All of this has been fixed in my pull request.
Of course, I don’t mind just using my own fork, but other people are trying to use PushPlugin as well. They don’t typically scrub the project forks.
Gotcha, ok, I’ll email the developer of the plugin to see what’s up with the pull requests… Thanks!
Thank you =)
Thank you very much for this needed tutorial. One question, I’m not getting the returned registration key? There’s no error alert or anything. I do see the “Register called” message but nothing after that. Any suggestions?
Thanks,
Phil
Hi Phil,
I followed the manual plugin installation procedure and I was having the same problem. So I ran the automatic installation with plugman, then followed the steps in this tutorial, and finally got the registration ID reply.
Sergio
Hi Phil,
Are you also trying with sample code
https://github.com/phonegap-build/PushPlugin/tree/master/Example/www
I am also running into error where in I am not able to see device getting registered ..Please let me know if you are able to pass that hurdle ..
Hi Raul,
Did you get the sample code working? I tried and was not able to get the registration. I’m trying this again over the weekend and hope to get it settled.
Phil
Holly,
Is there a way to handle the notifications when the app is not running? (for example: upload the device’s current location to a database in background when a push notification its recieved).
Holly,
This is great…one thing that would be great is a tutorial on how to use PhoneGap Build, Parse.com JS API, and PushPlugin….for iOS and Android. Any thoughts about this?
thanks,
Mitch
hey Mitch
did you ever get push working with Parse.com. I am just about to start down that track. Have a Javascript / phonegap app with the pushplugin enabled and want to use Parse.com to manage the push notifications.
hoping you may have nutted it out first and any help you have would be great – or sample code – cordova 3.0 and pushplugin 1.3.3
cheers
Darren
If I understand this correctly, it does not appear that there is any way to send GSM or APNS push notifications from a device w/o utilizing a server. Correct? There is no direct interface from the device to these cloud services for sending notifications w/o utilizing a server. Correct?
Hi,
This is working fine till displaying registration id in the device. I could see the registration alert in my android device. But After copying the notify.js and changing sender key and registration id I tried to run notify.js from command line. It showed me “Can not find module ‘node-gcm'” which I guess is coming from the first line of notify.js. Please help.
I try with code examples in node-gcm’s readme and notify.js works for me. Please see https://github.com/h2soft/node-gcm#usage
Update on my previous comment:
When I changed the first line to say “.lib/node-gcm” it did not show any error. But when I run “node notify.js” from command line it show “null”. Please help me with what and how I should do…
I didn’t receive any message or notification when my app is opened?Could u help me.
Thank’s for such a Great Tutorial….But i’am Really emcountering the following problem.
I’am facing this problem since from last 4 days,tried many solutions from internet but getting the same error again and again.
The problem is
after running node notify.js on the command line it is returning me “null”.
—>what is that null and i supposed to get the alert on the device but it’s not getting pls help me in resolving this issue..
Regards
Gopal
I am not able to replace the default PhoneGap icon with my own icon for the Application. In config.xml, is used to specify the app icon and I replace the icon.png at the www root directory with my own png (128×128).
Thanks.
i created the index.js but i am not getting the registration alert as you got in the tutorial above .
Hi Holly,
I did all things as described and i was able to get the Registration ID, not the push message.
Details :
Phonegap Build Verison : 2.9.0
Node js returned null from the gcm send method.
Seems everything in my side is fine.
Please Help
Hi,
Is there any plugin insteadof ‘navigator.notification.activityStart(”, ‘Loading …’); in IOS
I have a app that I am building with phonegap build. Will pushwoosh plugin support push notifications for Windows 8, I know it is already supporting IOS and android.
Hi Holly,
thanks for the blog post. I tried it and it worked “out of the box”
These posts are immensely useful. THANKS
Hi Holy,
Thanks for the blog. It is really useful, and I have got it whole thing working end to end when I followed the blog.
I have a quick question.
I am using HTTP post method to send a push notification to GCM server thru HTTP client. I am receiving the messages on my Android device. But the problem is that in the notifications area, I only see the last message when multiple messages are one after the another. I want all the alerts listed one after another as they get sent.
Also, it does not look the notifications are appearing on the screen top when it is locked.
Do you know how I can solve these 2 problems as well? Thanks in advance for your help!
My HTTP post request body in json format :
{
“registration_ids” : [“APA…..”],
“data” : {
“title” : “My Title”,
“message” : “My Msg”,
“msgcnt” : “1”,
}
}
Can somebody please help me?
hi Holly,
thank you for this great tutorial, I followed it step by step and got everything working for Android, but I’m having trouble getting notification to ios after I’ve downloaded the app from Phonegap-build ( when I test it localy from Xcode the notification works ok)
after I download the app from phonegap-build and run it on the device I get this in console:
Use of the tag has been deprecated. Use a tag instead. Change:
To:
I have this on www/config.xml
what am I missing?
www/config.xml:
gap:plugin name=”com.adobe.plugins.pushplugin”
Hello,
I was facing an issue with the onNotificationGCM.
The successHandler gets fired, but after that the onNotificationGCM does not get fired.
If anybody could help me with the issue.
I’m having the same issue. The onNotificationGCM doesn’t fire so I am not getting the registration id back. I have replaced the sender id with mine. What am I we missing? By the way, I am using myEclipse instead of Eclipse. Does that have to do with anything?
Probably Urban Airship, PushWoosh and Puship are not supported by Online Build but is more more simple than that!
try itself:
http://urbanairship.com
http://pushwoosh.com
http://puship.com
Hi Holly,
I followed through the steps for android, but when I compile to run for the first time (in step 2 of this tutorial), I get a compilation error:
-compile:
[javac] Compiling 8 source files to /Users/nadavelyashiv/Code/PushNotificationSample/platforms/android/bin/classes
[javac] /Users/nadavelyashiv/Code/PushNotificationSample/platforms/android/src/com/plugin/gcm/GCMIntentService.java:96: cannot find symbol
[javac] symbol : method getString(java.lang.String)
[javac] location: class com.plugin.gcm.GCMIntentService
[javac] .setTicker(getString(“title”))
[javac] ^
[javac] /Users/nadavelyashiv/Code/PushNotificationSample/platforms/android/src/com/plugin/gcm/GCMIntentService.java:95: cannot find symbol
[javac] symbol : method getString(java.lang.String)
[javac] location: class com.plugin.gcm.GCMIntentService
[javac] .setContentTitle(getString(“title”))
[javac] ^
[javac] 2 errors
BUILD FAILED
/usr/local/Cellar/android-sdk/r22.0.4/tools/ant/build.xml:720: The following error occurred while executing this line:
/usr/local/Cellar/android-sdk/r22.0.4/tools/ant/build.xml:734: Compile failed; see the compiler error output for details.
Any idea about what I’m missing?
thank you 🙂
Nadav
Hi Holly , I have an error “The connection to the server was unsuccessful(file:///android_asset/www/index.html)”.
Won’t work on phonegap/cordova 3.1.0
after installing “npm install -g cordova@3.0.9” this tutorial worked perfectly.
Part2 Step3 might need comma(,) at the end of curly bracket -> },
Hi All
Thanks for this tutorial, but I have a question, Is there a way to handle the notifications when the app is not running?
I saw in the logs that the plugin received the notification, but in the code the plugin check that the app is not running and save the message to later delivery, I think that this is an error, they suppose to lunch the app right?
Hey, another damn nice tutorial.
Is there any issues in running the app on an emulator? I tried it with two emulator configurations—
1. Android 4.3
2. Android 2.3.3 [w/ Google API and Google account configured]
The onNotificationGCM() method is never executed.
Any help on this? Anyone?
You must install google cloud messaging from android sdk manager and use gcm.jar.
This is the best tutorial where you can test it.
http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/
Stolen from
http://stackoverflow.com/questions/16713321/push-notifications-dont-work
@Anas
Check your AndroidManifest.xml file, I too had the same issue.
https://github.com/colene/PushPlugin/blob/master/Example/Sample_AndroidManifest.xml
Follow the above link.
Hi ,
1)
I have built a phonegap application which will return the Registration-Id and these ids are saved to the SQLServer
2) I have install nodejs to my system
3) I want to build a C# application in order to send the notification using this notify.js … How this can be achieved ?
If somebody can provide a sample code it will be appreciated.
Holly, thank you very much for the tutorial. Everything worked great off the bat (phonegap 3), however I have noticed that after closing and reopening the application the onNotificationGCM never gets called. Do I need to call “register” every time app opens up?
Also, after few minutes the app stops receiving notifications completely 🙁
Thank you
Hello Holly,
Thank you for the great tutorial. Can you please tell me if PushPlugin will support more platforms in the future (and if yes which exactly) or it was meant only for Android and iOS?
Thank you.
Regards,
SN
Great tutorial! Example app does not work with Cordova 3.1.0.
Apply this fix to ensure the app handles the push message correctly when the app is not running:
https://github.com/rubennorte/PushPlugin/commit/3a400752c583ce8e3f85b35c376946b2d10ad4fb
In the section “Part 2: Register the application with the Google Cloud Messaging service”, May I know what is the ecb parameter? and where can I get it?
Many thanks.
Hi,
Thanks for the tutorial. It works really great. I have a question. How can I display a notification count on the android launch icon??
Thanks in advance,
Jack
Hi,
Whoever is getting a build error of ‘PushPlugin’ not supported should change the com.adobe.plugins.pushplugin to com.phonegap.plugins.pushplugin in www/config.xml
Hi,
Thanks for the tutorial.
I has tried many time, but “title” still show App name. How to modify that?
message.addData(‘title’,’Push Notification Sample’ );
Cheers
Hi,
Whoever is getting ajax request problem may change the repository config.xml file found in res/xml/config.xml
change access control origin like this
sorry change the access control origin like this way
Very Good!
Work 100%!!
Thank you!
In the github example code, I notice that in the xcode project you’re including phonegap.js from index.html, and the file doesn’t even exist. Not only that, but there is no code that is functioning, it is just a stock template.
Has anyone even got push notifications working in phonegap 3.0? At this point it would easier to go full native.
if you’re developing locally from your xcode you need to include the cordova.js file, the phonegap.js reference is when you upload the www folder to phonegap build.
also if you can add the push notification plugin from cordova command line interface by doing “cordova plugin add https://github.com/phonegap-build/PushPlugin”
and don’t forget to add this in www/config.xml:
“”
apparently xml tags are stripped..so add the stuff described in https://build.phonegap.com/plugins/279 in www/config.xml file
Hi, and thanks for answering my question.
I know that for phonegap build the file is injected when it’s being compiled, I was under the impression this was for a local xcode project. Maybe it’s for both phonegap build and local.
I believe that I was looking at this link yesterday: https://github.com/hollyschinsky/PushNotificationSample30/ under the xcode part of it. In there, there’s a phonegap.js reference but no file.
And there is actually IS code there. I’m trying to think about if I’m looking at the right directory here, but regardless, it seems to be fine. There are small oddities that I’m not going to bring up, I’m just going to try and try again. I think I’ll get it this time :).
Hi, and thanks for answering my question.
I know that for phonegap build the file is injected when it’s being compiled, I was under the impression this was for a local xcode project. Maybe it’s for both phonegap build and local.
I believe that I was looking at this link yesterday: https://github.com/hollyschinsky/PushNotificationSample30/ under the xcode part of it. In there, there’s a phonegap.js reference but no file.
And there is actually IS push code there. I’m trying to think about if I’m looking at the right directory here, but regardless, it seems to be fine. There are small oddities that I’m not going to bring up, I’m just going to try and try again. I think I’ll get it this time :).
Okay, I found the solution to a major issue I have been having. The majority of the problems I have been having can be boiled down to not being able to debug the application. I had set up and compiled an iOS PhoneGap 3.0 or 3.1 app using the CLI, and found that after installing plugins was not working. For some reason, the CLI seems to have to set me up with cordova.js project files, but a phonegap.js project link.
This is why my push plugin was not working. When trying to set up the console logger to see why that was working, that didn’t work either! It was only after looking at the source code for a project called puship that I was able to find out my problem.
I just changed phonegap.js to cordova.js. I just also found out that the source from this page (https://github.com/hollyschinsky/PushNotificationSample30/tree/master/platforms/ios/www) seems to have this problem as well.
Am I going crazy or is there kind of an issue here?!
I would suggest to leave that project and focus on what is best for your project.
in terms of debugging you can either use the xcode console (make sure you add the cordova console plugin) or you can use weinre http://people.apache.org/~pmuellr/weinre/docs/latest/, which is a firebug like console you open up from your computer, you should probably use that because its much better method to debug.
hope it helps out 🙂
Hi Holly,
As per i tried the procedure above for push notification i got the reg id in android but when i send a notificatio by the server key and reg id get by the app but it returns NULL when i execute the notify.js…i hope u understand my problem thanks for the response in advance…:)
Hi Holly,
As on my previous question the notification is sent to the device on which i install the app with its reg id but my app is installed on many android phones so is i need to get their reg id or they got the notifications…Thanks for your response advance…:)
Thanks a bunch Holly! Keep up the good work.
If anyone struggles with ‘module not defined’ in PushNotification.js, like I did. Then it’s because you’ve copied the wrong file (that contains the wrapped module).
Hi, Barsum! I’m having the “module not defined” issue, but can’t figure out wich file are you talking about (‘copied the wrong file’)… which file should I copy?
Thanks in advance!
There isn’t an issue with copying the wrong file – you have the right one. The issue is that there is a defect in that file on like 66. Change line 66 to look like this:
if (typeof module != ‘undefined’ && module.exports) {
Hi to all, I’m currently working on the solution which provides push notifications to Phonegap, Codova, Titanuim and other similar frameworks. Soon we will have the first version of this plugin. If you’d like to see what we have done, or just to test it you can contact me at zeljka.janda-hegedis@infobip.com.
Thanks Holly for this tutorial.
Sorry for my poor English.
I have created an app using your steps. When i am trying to build this on https://build.phonegap.com/apps it is showing an error “plugin unsupported: com.adobe.plugins.pushplugin”. Could you tell me why this error is showing.
In config.xml change the name attribute on the plugin line to: name=com.phonegap.plugins.pushplugin
It returns NULL because there is an error in the tutorial.
Replace this line:
sender.send(message, registrationIds, 4, function (result) {
With this one:
sender.send(message, registrationIds, 4, function (err, result) {
As you can see here: https://github.com/ToothlessGear/node-gcm – the callback function you pass to sender.send() expects 2 params: err and result. However this tutorial passes only one param – err. On success you receive no error, hence you log NULL.
Other than that – what a useful and easy to follow tutorial. Thank you!
Thank you for this tutorial, is very hepfull, you have to update some line of code, but globally is a very good tuts
Nice Tutorial!
I am not able to get back a registration ID for my device when I try to run the application.
I keep getting a JSON exception: No value found for “sender_ID”. Any idea why I get this exception ?
Hi Holly, Hi all,
Thanks for the tutorial. I implemented a push request class on my php server, so that I can send POST requests to GCM server with cURL, works like a charm ! 🙂
However i got a question…I’d like to know if that’s possible to send more than once notification to one device ? I mean that i only have the latest notification received on the device, but not the previous ones…I tried it with the collapse_key but doesn’t seem to help me. Any ideas ?
Thanks a lot !
How to set the notification badge number on my application icon, i am using above code to get the GCM API key.
we got the GCM API key and got the notifications but my problem is how to set the badge number on my app key?
In regard to Bikash’s comment, the config.xml line for the plugin should be:
instead of:
if you are receiving the error “plugin unsupported: com.adobe.plugins.pushplugin”
It works, thanks.
Greetings all,
Holly, thank you for the tutorial, first I am new to PG and I’m sort of feeling my way around. I have a running app, however using eclipse I followed the auto and manual setup for Push Notifications right away I get error in the PushPlug.java file. I hover over the error and select the first available “quick fix” most are resolved except for this:
private Context getApplicationContext() {
return this.cordova.getActivity().getApplicationContext();
}
I can not resolved “getActivity” the error says “The method getActivity() is undefined for the type String”
Am I missing a step
Greetings,
Thank you for the great tutorial.Really helped me. Is there a way to add a custom icon to the notification ?
Thank you
1 and Wi-Fi connectivity, built-in 2 MP front HD and a full multi-touch support webcam for video chatting and conferencing, and a 5Mp rear camera with a flash. Most people use the terms magazine and laptop computer interchangeably.
I’ve been banging my head against the wall for two days installing the plugin manually and integrating it with my app. Whenever I sent a push message with the application open, it would crash immediately (Sorry, application has stopped working). When the app is closed and I send a push, nothing happened.
I checked the logcat through the aLogcat app, but it would show me nothing was wrong or logged (and the drivers don’t exist for my tablet so I can’t use adb correctly…bummer). After upgrading components, commenting out code in the plugin and my code, I finally tried to run it on an emulator since I know I can get the logcat more reliably. It’s not as hard as it would appear. You already have the gcm.jar installed – all you have to do beyond that is make sure you are using a Google API as your target, and add your google account the same as you would your physical device.
Once I did this, I saw the problem immediately. The plugin needed access to GET_TASKS in the android manifest. So adding the following line to the android manifest file worked.
uses-permission android:name=”android.permission.GET_TASKS”
Hope this helps someone else who might be having a similar problem. I checked the plugin documentation and it doesn’t appear to be on the github site or readme. FYI…I was using Cordova 2.9.1 and testing on API level 17.
Cheers
Dear David,
I have tried running the app on an emulator (Nexus S) and it just does not return the onNotificationGCM callback, to show the registered id.
On my Android Samsung Galaxy S4 device it works perfectly, but on the emulator it does not return that callback at all. Is it because I havent added my Google Account to the Nexus S emulator or what could be causing the onNotificiationGCM callback to not be returned only on the emulator?
@Holly Thank you for the great tutorial. I see many people are having this same error – any advice for using the code on an emulator and having the onNotificationGCM callback returned?
I am using Cordova 3.3.0 and Android API 19.0.1
Thanks in advance,
Ruan
I have found a subsection of a lengthy article, that may provide a fix:
http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/
Scroll down to: Installing helper libraries and setting up the Emulator
This section will explain how to get the push notifications working on the emulator and will hopefully allow the onNotificationGCM callback to be returned successfully.
Summary:
1. Add the gcm.jar to the Android project.
2. Add your Google Account to the emulator.
After many hours I have found that the Wi-fi network I am on has blocked some ports that had to receive the GCM notification, so the app was registering the Android device properly with GCM and the server API key was also valid and the node service was working properly, but the messages weren’t reaching the Android device, as the wifi network was blocking some of the necessary ports:
“The ports to open are: 5228, 5229, and 5230. GCM typically only uses 5228, but it sometimes uses 5229 and 5230.”
As referenced from:
http://stackoverflow.com/a/11801835/2728686 and http://developer.android.com/guide/google/gcm/gcm.html
Make sure these ports are open or use your mobile data connection and not wifi, if your wifi connection may be blocking those ports.
Hope this helps someone!
Also, if you copy the native java code mentioned in the adobe article from Holly, when you replace the YourActivityClassName.class with your class that extends droidgap, you will probably have to import it at the top of the file since the GCM plugin is in a different package.
Great tutorials, thanks Holly!
Sorry, that link is here:
http://www.adobe.com/devnet/phonegap/articles/android-push-notifications-with-phonegap.html
Hi Holly;
thanks for all the tutorials. your’s are just about the only ones out there and are truly helpful.
my question is regarding your following statement:
“GCM will always return a message indicating if a device id has changed or is invalid”
to whom will the GCM sernd the message: to the 3rd party app server? or to the mobile device?
if to the 3rd party server, how can the mobile device know this and re-register?
if to the mobile device, I assume I should re-register and send the new reg id to the 3rd party server?
thanks for your help
Guy.
GCM will return an error or canonical id in its return message to your third party server, it is up to your server to read and parse the response and match it to the original sender. Google recommends that you update your database if a new registration id is matched. There should be no action required by the mobile device – since the app registration or uninstall that was captured by Google is what generated the new id (or error) in the first place. If GCM returns an error, again, you have to parse it and decide on the remedy – depending on the message.
Hi, the callback function “onNotificationGCM” does not trigger when the app is closed and receive notification/message?
REgards,
Manjunath T
having the same issue here…
see my post on http://bit.ly/1f9f3M6
can someone please comment or provide a way to get background event to work?
thanks,
Hello,
I tried a lot of stuff but I’m still stuck on the same issue.
When I run the app through Cordova CLI in emulator, SuccessHandler is called and display the success message but OnNotificationGCM is never fired. So I cannot register the device.
Can you please gimme some help, at least how to debug and see what happend when .register is used.
Thanks
Hi Jeff, try running the adb logcat tool from the command line for more debug information on what’s happening when it’s running on the emulator. You may want to start that in one console and open another to run your app and then look for messages in the console running logcat. Also, this link may be helpful: http://stackoverflow.com/questions/12404012/gcm-register-didnot-work-on-my-emulator – as far as targeting an emulator versus a device as you need to make sure the emulator meets the requirements to support GCM.
Hope that helps!
Holly
Thanks for your answer. The logcat tells :
V/GCMRegistrar( 850): Registering app **MYAPP of senders **MYSENDID
W/PluginManager( 850): THREAD WARNING: exec() call to PushPlugin.register blocked the main thread for 93ms. Plugin should use CordovaInterface.getThreadPool().
W/ActivityManager( 378): Unable to start service Intent { act=com.google.android.c2dm.intent.REGISTER pkg=com.google.android.gsf (has extras) } U=0: not found
D/ConnectivityService( 378): [CheckMp] isMobileOk: not connected ni=NetworkInfo: type: mobile_hipri[UMTS], state: DISCONNECTED/IDLE, reason: (unspecified), extra: (none), roaming: false, failover: false, isAvailable: true, isConnectedToProvisioningNetwork: false
I/Choreographer( 850): Skipped 39 frames! The application may be doing too much work on its main thread.
Hi Jeff, make sure that you have your AndroidManifest.xml set up according to the manual setup in the PushPlugin documentation https://github.com/phonegap-build/PushPlugin and that your Intent in there says com.google.android.c2dm.intent.REGISTRATION and not com.google.android.c2dm.intent.REGISTER. Thanks, Holly
Thx but in the manifest it’s right : REGISTRATION
If you have not figured it out yet your simulator must be running google Api level18/19 etc and not
android 4.4.2 level 18/19 for this to work. change the target of your device to one of these.
Holly;
can you please advice on mine and @Manjunath comment regarding not being able to get background notifications to work? also see (http://bit.ly/1f9f3M6)
thanks a lot!
Did you try to run adb logcat? Is this on a real device or emulator? Try putting some debug code in the onNotificationGCM function to see if it being called and put it in a console.log call. Did you copy the native java code to the notification files downloaded from the push plugin and remember to identify your activity class file? You can try sticking some log code in the java class as well to see if it is even being called when your app is in the background or not running (it should wake up the app up via intent if its wired correctly). Are you receiving notifications when the app is running?
Hi, thank you for the tutorial.
It works like a charm and really helped me as I am new to the mobile development.
However, can you be more specify how to set the badge number from the PushPlugin API?
My apps will never display the badge number no matter how many notification is received for both android & IOS platform. PS: I am utilizing the provided sample app (PhoneGap version prior to 3.0)
Thanks & Regards.
Hi,
I’m working in a Chat developing with firebase and javascript. Now, I want to use a phonegap for my webapp run on Android. But my problem is that I haven’t any server, because with firebase this isn’t necessary, therefore I need to send notifications with javascript from client side. Then I need a file like your notify.js but for javascript not for node. It is possible? how? There are a library of havascript to use?
Thanks.
Hi Holly
Thanks for great tutorial . I got the correct output for android. how to use the same to code for IOS?
im using windows Is it possible to work for IOS in Command line interface in windows????
hey
i want device to device communication through one android device to another android device directly,
without using gcm.
i dnt want to any third party server, means ( android-> gcm server-> android )
i have the android device id.
can u please give me the some sample code……
hey
i want device to device communication through one android device to another android device directly,
using gcm.
i dnt want any third party server, means ( android-> gcm server-> android )
i have the android device id.
can u please give me the some sample code……
Hi,
For any of you having problems with the registration callback (“ecb”) never being called, make sure to enable the “Google Cloud Messaging for Android” in the console, as described here: http://stackoverflow.com/a/19565728
When trying to send a Push test from Node I am getting:
“results”:[{“error”:”InvalidRegistration”}]}”
On its face this seems simple enough…my registration device code is wrong. However, I am nearly 98.5% sure it is correct! Is there any other trouble shooting that can be done? Is there anything logged on GCM?
I have tried node.js and CURL
url –header “Authorization: key=%api_key%” –header Content-Type:”application/json” https://android.googleapis.com/gcm/send -d “{\”registration_ids\”:[\”REG_ID\”]}”
Any insight is appreciated.
can i use this to set reminder that have exact time and date to fire. app in closing mode.
Hi, thanks for your tutorial, i applied this but it shows an alert “No value for ECB”
Updated Comment!
Hi, Your tutorial is completely works for me, now my app rum smoothly…
Firstly i faces soo many gotchas but my now i am happy 🙂
Thanks For such a nice tutorial
Regards
Adeel Hussain
Thank you holly u did great work perfect article it help me to set up push notification in my app but when i receive the push there is no sound just vibration even if i set soundName in the server and put the sound file into www forlder (am using phonegap build) any suggestion?
I have a problem with the cordova registration id does not appear and I do not know if it’s the version of cordova that I can do?
Hi Holly Schinsky, I trying to follow your tutorial but I’m stuck, because i using DreamWeaver htlm5, and I haven’t found a tutorial for html5, it’s because I want to deply for IOS and Android but I know I have to use different coding in html5 when trying to send push notifications.
Hope you can help me.
Thank you
Thanks man, that tutorial works perfect for me!
@jimmy: What’s the problem? Do you get any errors?
Hello,
I followed your tutorial step by step , but I have a problem : server returns “mismatchsenderid”.
Also I used browser key and server key from Google Console.
The application has Android 4.4.2(API) and my device has Android 4.1.2, I don’t know if this is the problem.
Please help.
Thanks,
George
Hi, thanks for the tutorial!
I was wondering if it’s possible to do notifications without using the push mechanism – i.e to have the app schedule a notification to appear at a certain time?
I’m very new to this mobile dev stuff, so please forgive me if this is a particularly stupid question!
Thanks!
Perfecto !!!
Hi Holly.
Thanks for sharing your great article, i could be able to send push notifications to the app on device. I was really felt happy that every thing works great from your article. In the second part, you are using node-gcm(to communicate with gcm) to send notifications to the registered devices. We have developed google app engine for our development purpose, so is there any other alternative to node-gcm to send notifications.
– As per docs of GCM, the app on the device has to send registration id to our server(Google App engine) once it gets it from the gcm. but here we are hardcoding the regid and server api key. So is notify.js is working as a server here? Could you please tell me how to send a notification by sending regid to the server and server will send message to the gcm?
Thank for the tutorial but my issue I have tried this tutorial several times, I only get Call Success: OK notification. I don’t see any Registration Key notification. Kindly tell me what is the issue.
Thanks in advance
Hello,
I am using phonegap build 3.5.0 and have added the following references:
in my index page
in my config.xml
It doesn’t work, however, unless I manually include the PushNotification.js in the root of the zip file that I upload to PhoneGap Build. I thought that perhaps PhoneGap Build wasn’t injecting the plugin files, so I downloaded the apk file and had a look inside and sure enough in the ‘assets/plugins/com.phonegap.plugins.pushplugin/www’ folder I see the PushNotification.js file is there. So my index file references the PushNotification.js in the root directory and PhoneGap is injecting the file in the’../com.phonegap.plugins.pushplugin/…’ folder which is an obvious disconnect between the two. So what am I doing wrong?
Thanks
Hello,
I am using phonegap build 3.5.0 and have added the following references:
in my index page
script type=”text/javascript” src=”PushNotification.js”
in my config.xml
gap:plugin name=”com.adobe.plugins.pushplugin”
It doesn’t work, however, unless I manually include the PushNotification.js in the root of the zip file that I upload to PhoneGap Build. I thought that perhaps PhoneGap Build wasn’t injecting the plugin files, so I downloaded the apk file and had a look inside and sure enough in the ‘assets/plugins/com.phonegap.plugins.pushplugin/www’ folder I see the PushNotification.js file is there. So my index file references the PushNotification.js in the root directory and PhoneGap is injecting the file in the’../com.phonegap.plugins.pushplugin/…’ folder which is an obvious disconnect between the two. So what am I doing wrong?
Thanks
Reply
I should point out that the plugin reference is to com.phonegap.plugins.pushplugin and NOT com.adobe.plugins.pushplugin
Hello,
Is it possible to add a different icon as part of the notification versus a default icon for each one?
Relevant pull request: https://github.com/bobeast/PushPlugin-deprecated/pull/6
I am having a strange problem with push sounds. When my app is running in IOS8, the push notification works in that it plays my beep.wav file. However, when the IOS app is closed, the push notification sound is the default notification beep. Does anyone know why my beep.wav file only plays when my app is open?
I’m using cordova for visual studio if that matters and my beep.wav file is in the root folder which is the same folder that my index.html file is in.
Now https://github.com/phonegap-build/PushPlugin.git plugin also provide the push notification service for blackberry10,
And,I was trying to implement the same for blackberry and with this i was able to register my device with PPG server but was not able to receive the notification.
For server side i have used Push service sdk provided by blackberry.
My server push initiator returned with status 1001 means request was received with PPG server but was not able to process.
I was not able to get where actually problem.
Please help me if someone had done push notification using cordova for blackberry.
Thanks,
Hi Holly Schinsky,
I am really stuck with implementing push notification in Blackberry 10,
I had added problem in brief in my previous post.
I will really thank full if you will get me out of this.
Let me know if required to add my code here.
Chetan,