Tutorial: Implement Push Notifications in your PhoneGap Application

July 17, 2013By 135 Comments

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
Part 2 in the slides here goes along with this guide and may provide extra detail.

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.

Note this code also has basic support for handling iOS push notifications. You will just need to assign your own push-notifications enabled certificates through PhoneGap Build to build and test it.

WARNING – PHONEGAP 3.0 USERS

PhoneGap Build support for PhoneGap version 3.0 should be available around the end of September ’13. In the meantime you can use the PhoneGap CLI and build locally with your devices to try out this tutorial, or use a version prior to 3.0. A full working sample with PhoneGap version 3.0 can be found on my github account 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)

  1. Create a basic PhoneGap project
    $ phonegap create PushNotificationSample --id "com.pushapp" --name "PushNotificationApp"
  2. cd into the newly created project folder
    $ cd PushNotificationSample
  3. Build the application for Android (also adds it as a platform under the /platforms folder)
    $ phonegap local build android
  4. Install the PushPlugin from its github location via the PhoneGap CLI:
    $ phonegap local plugin add https://github.com/phonegap-build/PushPlugin
  5. 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
  6. 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:

  1. Add the following script line to your index.html to reference the PushNotification plugin.
    <script type="text/javascript" src="PushNotification.js"></script>
    
  2. 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" />
    
Don’t confuse this with the config.xml file specified per platform.

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.

  1. 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"});
    
  • Next code each of the callback functions referred to in the above registration call:

    1. 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)
          },
      
    2. 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);
      },
      
    3. 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;
              }
          }
      
      
    You could manually add the plugin to your application outside of PhoneGap Build as well, see the PushPlugin readme for more details.

    Run your application

    You have a few options you can choose to run your application…

    1. 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
    2. 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
    3. 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:

    android-notify-reg

    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…

    1. 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.
      You must have node installed for this to work.
    2. 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.
    3. 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.
    4. 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.
    5. TIP: Copy and paste the registration id from the console where you’re running your application to avoid typos. You can use adb -d logcat from the command line to show the android console. This is also useful for debugging in general.
      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);
      });
      
      Other options you may want to set for your message are a collapseKey value or a delayWhileIdle value (defaults to false but set to true to have GCM hold the message until the device is not idle). I recommend reading this link on advanced GCM settings for more details.
    6. Now type the following from the command line where the script was created to run the code and send a push notification:
      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):
      droid@screen-1b

      When clicked on, the application should open and you should see this alert popup showing the message data:
      droid@screen-2a

    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.
    There are other 3rd party Push Notifications plugins available for services such as Urban Airship, PushWoosh etc with similar API calls that can be used as well but are currently not supported by PhoneGap Build.

    Differences between Android and iOS

    1. Android payload size is 4k whereas iOS payload size is 256 bytes
    2. 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.
    3. 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.
    4. 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.
    5. 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: AndroidCordovaPhoneGapPush Notifications Tags:

  • About the Author ()

    Comments (135)

    Trackback URL | Comments RSS Feed

    1. PG says:

      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

      • Jasper Ng says:

        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

    2. Brandon says:

      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

    3. Michael says:

      Nice write up, thanks!
      Would be nice if there was more info on using the push plugin without pg build.

    4. PG says:

      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

    5. ben says:

      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

    6. ben says:

      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

      • ben says:

        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!

    7. Dan says:

      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

    8. Ruhi says:

      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.

    9. Denis says:

      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?

    10. Wade says:

      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

      • raul says:

        hi Wade,
        were u able to figure out the problem and get it running ? I am also running into same issue…

      • Phillip says:

        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.

    11. Jason Farnsworth says:

      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.

    12. Phil says:

      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

    13. Arturo says:

      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).

    14. Mitch says:

      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

      • darren says:

        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

    15. Steve says:

      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?

    16. Gowtham says:

      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.

    17. Gowtham says:

      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…

    18. Ruhi says:

      I didn’t receive any message or notification when my app is opened?Could u help me.

    19. Gopal says:

      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

    20. Tek Mun says:

      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.

    21. dillion says:

      i created the index.js but i am not getting the registration alert as you got in the tutorial above .

    22. santhosh says:

      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

    23. Dhanesh says:

      Hi,
      Is there any plugin insteadof ‘navigator.notification.activityStart(”, ‘Loading …’); in IOS

    24. Olga says:

      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.

    25. gary says:

      Hi Holly,

      thanks for the blog post. I tried it and it worked “out of the box”

      These posts are immensely useful. THANKS

    26. Leela says:

      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″,
      }
      }

    27. Itay says:

      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?

    28. Bhavika says:

      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.

      • Tintin says:

        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?

    29. Fede says:

      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

    30. Nadav says:

      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

    31. Tumza says:

      Hi Holly , I have an error “The connection to the server was unsuccessful(file:///android_asset/www/index.html)”.

    32. Taywi says:

      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 -> },

    33. Jorge says:

      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?

    34. Anas Azeem says:

      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?

    35. Salma says:

      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.

    36. Mike says:

      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

    37. SN says:

      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

    38. 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

    39. Toni says:

      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.

    40. Jack says:

      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

    41. Moin Uddin says:

      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

    42. Ethan says:

      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

    43. Dibeesh says:

      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

    44. Very Good!

      Work 100%!!

      Thank you!

    45. Brandon says:

      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.

      • itay says:

        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:

        • itay says:

          apparently xml tags are stripped..so add the stuff described in https://build.phonegap.com/plugins/279 in www/config.xml file

        • Brandon says:

          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 :).

        • Brandon says:

          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 :).

        • Brandon says:

          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?!

          • itay says:

            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 :)

    46. 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…:)

    47. 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…:)

    48. Barsum says:

      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).

      • Fabio says:

        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!

        • Gregory Pierce says:

          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) {

    49. 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.

    50. Bikash says:

      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.

    51. 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!

    52. Mohamed says:

      Thank you for this tutorial, is very hepfull, you have to update some line of code, but globally is a very good tuts

    53. Samaresh says:

      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 ?

    54. Thom says:

      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 !

    55. anuradha says:

      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?

    56. J Belfore says:

      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”

    57. Chris says:

      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

    58. Ananth says:

      Greetings,
      Thank you for the great tutorial.Really helped me. Is there a way to add a custom icon to the notification ?

      Thank you

    59. Dionne says:

      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.

    60. david says:

      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

      • Ruan says:

        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

        • Ruan says:

          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.

          • Ruan says:

            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!

    61. david says:

      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!

    62. guy says:

      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.

      • david says:

        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.

    63. Manjunath T says:

      Hi, the callback function “onNotificationGCM” does not trigger when the app is closed and receive notification/message?

      REgards,
      Manjunath T

    64. JeFF says:

      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

        • JeFF says:

          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.

    65. guy says:

      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!

      • david says:

        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?

    66. Sunny says:

      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.

    67. Paco says:

      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.

    68. bharthi says:

      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????

    69. paramvir says:

      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……

      • paramvir says:

        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……

    70. Grrd says:

      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

    71. Kevin says:

      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.

    72. saw says:

      can i use this to set reminder that have exact time and date to fire. app in closing mode.

    73. adeel says:

      Hi, thanks for your tutorial, i applied this but it shows an alert “No value for ECB”

    74. adeel says:

      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

    75. Ray says:

      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?

    Leave a Reply