Tutorial: Android Push Notifications with PhoneGap

October 25, 2012By 100 Comments

My last post covered push notifications with PhoneGap on Apple devices, but I also wanted to cover push notifications with PhoneGap on Android for those developing cross platform applications. I found that I was able to get my notifications working much faster on Android comparatively.

Google Cloud Messaging

Android push notifications are available via the Google Cloud Messaging – GCM service (similar to Apple’s Push Notification Service). Previously they were supported through C2DM (Cloud to Device Messaging framework) but that API has since been deprecated and the Google Cloud Messaging services adds enhancements above and beyond what C2DM offered. There’s a Cordova/PhoneGap plugin available to aid in working with the Google Cloud Messaging service. The message size allotment for the GCM payload is 4kb (String data only), noticeably bigger than the Apple Push Notification requirements of 256 bytes. There’s an article about the types of messages that can be sent in detail here. Also, I suggest you look over the documentation for using this service in general here when building your application, there are a lot of details I will not cover in this post. Some points I wanted to highlight from that article are:

  • GCM makes no guarantees about delivery or the order of messages.
  • An Android application on an Android device doesn’t need to be running to receive messages. The system will wake up the Android application via Intent broadcast when the message arrives, as long as the application is set up with the proper broadcast receiver and permissions.
  • It does not provide any built-in user interface or other handling for message data. GCM simply passes raw message data received straight to the Android application, which has full control of how to handle it. For example, the application might post a notification, display a custom user interface, or silently sync data.


The steps for setting up push notifications in your Android application are:

  1. Create a new Android Cordova project either via the command line tools or Eclipse (command line recommended)
  2. Download the GCM Cordova Plugin
  3. Follow the steps in the plugin’s Readme
    • Don’t forget to setup your Google Cloud Messaging Account as noted in the readme and note your project id located in the URL. For instance the number in bold below is the id you need to send in the register() function:

    • Don’t forget to change the following to use your GCM project id (from the step above)
                                 window.GCM.register("your_sender_id", "GCM_Event", GCM_Success, GCM_Fail );
                                 window.GCM.register("824841663942", "GCM_Event", GCM_Success, GCM_Fail );
  4. Add code handling for the actions to take when the application receives a message while open or not (ie: display a popup alert, status bar notification etc).
    Note: The plugin handles registering with GCM and has methods for receiving a message, however it does not actually provide the notification code itself, this is something you need to add. Read on further for how to add native code to produce a status bar notification.

If you need more information about GCM project creation, specific steps can be found here.

The plugin includes a sample project already setup to register for push notifications (includes the AndroidManifest.xml changes and plugin configuration already), all you have to do is edit the CORDOVA_GCM_script.js file to use your GCM sender/project id in the register function and you can run it immediately or use this project as a reference while making the changes to your own.

If you prefer to use Eclipse for your editing, you can simply import your existing Android project that you just created above (or the sample included in the plugin) and start working from there. Choose File | New | Project, then you will see the following dialog, where you will select Android Project from Existing Code as follows:

Running the Sample Application

When you run the sample code from the plugin, it will automatically try to register your device. If registration is successful, you should see a message containing the registration token id as I circled below in the screenshot of mine running on my Galaxy Tablet:

You should also see the following trace in your console:

10-24 18:24:20.720: V/GCMReceiver:onRegistered(21989): Registration ID arrived!
10-24 18:24:20.730: V/GCMReceiver:onRegisterd(21989): {"regid":"APA91bFobAwM7P3Okxy2al8RI12VcJFUS-giXWTOoWXIObtSPOE1h7FuH1VPLBPgshDI_Fp7aIYVET-ssvGUErlWYA0cKPGhoXT1daqyDsEfem9ZtgZNRhQFv7kLCIVSigYlpMluToPiSHSsFSEdtCDfKoOZqNPsfg","event":"registered"}
10-24 18:24:20.730: V/GCMPlugin:sendJavascript(21989): javascript:GCM_Event({"regid":"APA91bFobAwM7P3Okxy2al8RI12VcJFUS-giXWTOoWXIObtSPOE1h7FuH1VPLBPgshDI_Fp7aIYVET-ssvGUErlWYA0cKPGhoXT1daqyDsEfem9ZtgZNRhQFv7kLCIVSigYlpMluToPiSHSsFSEdtCDfKoOZqNPsfg","event":"registered"})

Once you have obtained a registration id as above, you can write server code (see the section below on using Node.JS code to send a message to your application) or use a service like Urban Airship or PushWoosh to start sending notifications. When a message is received, you will see additional text displayed as shown in the screenshot below:

At this point though, the plugin does not contain anything more to actually show a status bar notification or otherwise notify you. The next section covers how you can add some additional code to it for showing a status bar notification when the message is received.

Status Bar Notification

Since the plugin simply receives the message (whether running or not) but doesn’t do anything with it from there, you have various choices for what you could do with it. One common thing is to show a message in the native status bar. Note that on iOS the process is different and the notification is automatically shown, but on Android you have to explicitly code for it. You could use the Cordova StatusBarNotification plugin along with this one, or if you want a faster solution, you could simply add the following native Java code into your GCMIntentService.java onMessage() function:

          String message = extras.getString("message");
    	  String title = extras.getString("title");
    	  Notification notif = new Notification(android.R.drawable.btn_star_big_on, message, System.currentTimeMillis() );
    	  notif.flags = Notification.FLAG_AUTO_CANCEL;
    	  notif.defaults |= Notification.DEFAULT_SOUND;
    	  notif.defaults |= Notification.DEFAULT_VIBRATE;

    	  Intent notificationIntent = new Intent(context, TestSampleApp.class);
    	  PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
    	  notif.setLatestEventInfo(context, title, message, contentIntent);
    	  String ns = Context.NOTIFICATION_SERVICE;
          NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns);
          mNotificationManager.notify(1, notif);

Also, don’t forget to add these imports at the top of the file to support the above code:

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
Be sure to replace YourActivityClassName.class with the name of your stub class that extends DroidGap. For instance, in the sample project it is called MainActivity.

The above code sets the notification to include a star icon, vibration and the default sound. An example of it running on my Android Galaxy Tablet is shown below (circled in red).

When you click on the notification, the app will open and look like the following, showing that a message was in fact received:

Status bar notifications will be displayed differently depending on the type of device. Some Android devices will show them at the top versus at the bottom as shown in my screenshots…

Sending a message with node-gcm

There’s a Node.js library for sending notifications through Google Cloud Messaging as there was for Apple’s Push Notification Service as I showed in my last post. It’s called node-gcm, and below is the code I used to send my device a message (keys changed :)). In the Sender parameter you need to specify the API key that Google gave you when you registered for the Google Cloud Messaging service. You received two API keys, a browser and server key, either should work here, but if one does not, try the other :)! You also need to specify the token returned to your application when you registered using the plugin above. This is the registration id that was printed to the screen and console when you ran the application and called the GCM register function.

var gcm = require('node-gcm');

var message = new gcm.Message();
var sender = new gcm.Sender('AIzaSyCDx8v9R0fMsAsjoAffF-P3FCFWXlvwKgL');
var registrationIds = [];

message.addData('title','My Game');
message.addData('message','Your turn!!!!');
message.collapseKey = 'demo';
message.delayWhileIdle = true;
message.timeToLive = 3;

// At least one token is required - each app will register a different token

 * Parameters: message-literal, registrationIds-array, No. of retries, callback-function
sender.send(message, registrationIds, 4, function (result) {
/** Use the following line if you want to send the message without retries
sender.sendNoRetry(message, registrationIds, function (result) { console.log(result); });
You need to set the name of the title and message keys explicitly to title and message as the application plugin code is looking for that in GCMIntentService.java:

Bundle extras = intent.getExtras();
    if (extras != null) {
        try {
          String title = extras.getString("title");
          String message = extras.getString("message");

Collapse Key
According to the Android developer documentation, when you define a collapse key, it will only deliver the last one with a given collapse key, therefore saving the user from becoming ‘over-notified’ such as in the case of sports scores for example.

Also, note that these status bar notifications will be shown in the expanded list (if not dismissed yet) such as in the following:

Other Plugin Options

Lastly, I wanted to point out that if you are googling about Cordova push notification plugins for Android, you may also come across another one here. This one is supposed to be more specific to using notifications from PushWoosh, which I will cover in a future post with a sample. The plugin API more closely resembles the iOS Cordova PushNotification plugin, and interestingly enough still worked in receiving push notifications from my Node.js service completely outside of the PushWoosh service when I tested it (and I did not have to add the native Java code shown above to show the status bar notification) so I wanted people to be aware of it in case they wanted to try this plugin as well.

Filed in: AndroidCordovaMobile DevelopmentPhoneGap

About the Author ()

Comments (100)

Trackback URL | Comments RSS Feed

  1. Pavel says:

    just what i need in my app.
    will try to implement notification next week!

  2. ganapthi says:

    nice explanation.to use thankss

  3. Ar says:

    Great tutorial. It help me a lot. I have menaged to send test notifications with my php code and regid from Cordova-GSM. My problem is that I copy/paste REGID from eclipse to php script. Can you tell me how to send REGID from CORDOVA_GCM_script.js (or some other) to my server. Thanks.

  4. Hi Ar!

    You should be able to use something like this to call your PHP Script (or a node.js script) from the CORDOVA_GCM_script.js in the case statement where the registration token is received (right after this line: $("#app-status-ul").append(‘<li>REGISTERED -> REGID:’ + e.regid + "</li>");):

    function storeToken(token)
    var xmlhttp = new XMLHttpRequest();
    console.log("Token to register " + token);
    xmlhttp.open("GET", "http://myserver_url/register.php&quot;, true);
    xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4) {
    //a response now exists in the responseTest property.
    console.log("Registration response: " + xmlhttp.responseText);
    $("#app-status-ul").append(‘<li>SERVER RESPONSE ‘ + xmlhttp.responseText+'</li>’);

    Sorry it adds in some xtra chars in the formatting of the send method for the URL, but it should just be a GET call with the 2nd par being the URL to your PHP script (or other)…

    Hope that helps :)!!

    • Ar says:

      Thanks, work great 🙂

    • Vinod says:

      Hi Holly Schinsky,

      This is a great tutorial. I am able to register the mobile with gcm and received the regid. Please tell me the procedure to write the server side code and how to run it to send messages to my mobile.How to use php with node-gcm. When i do require(node-gcm) in my js file, it is not responding.Please give me a reply.

    • weward says:

      hi holly!
      1. how can send and store data to my server from this app using php? I cant do javascript.
      2. why did you use “GET” in this line: xmlhttp.open(“GET”, “http://myserver_url/register.php", true);
      3. If my php script is the same as that in the androidhive link that you gave(register.php) it is using post in the script. how would i be able to pass values to it from my app in CORDOVA_GCM_register.js?

      pls reply asap.
      all of you feel free to help me on this one.


      • weward says:

        ignore my previous question. i’ve already solved it. But I do have a new question about the unregistration of the app. The app registers a new regid every run. But it doesnt unregister from the server. how should the process be? kindly clear this one. TIA

  5. Thank you Holly,

    After a search for a Cordova Android GCM plugin, your tutorial confirms our findings of Mark Nutters plugin.
    Your tutorial puts the dots on the i, thank you for that… 🙂 (Your addition of the native Java status bar code fits perfectly!)

    We have some questions in regards to the following scenario:
    A user logs in to the application and at that moment a registration is made to the GCM. The regid is retrieved and returned to the server.
    1. In the example on every app access a new GCM regid is requested. Is this also the best practice for registration? (E.g. regid does not have a long lifetime?)
    2. If this is not necessary, how can the GCM_event method be registered without attaching it to the GCM.register command. (E.g. is there another method to call to set the event method without a new registration?)

    kind regards,


  6. Yariv Gilad says:

    Hey Holly
    Will you be posting any Flex/AS3 related content on this blog, or did you switch entirely to HTML5 related materials?

  7. Ida says:

    Does this CGM Cordova Plugin work with UrbanAirship? I’m developing a project with PhoneGap Android and I need to use UrbanAirship.

  8. Ida says:

    Anybody else has any idea?
    Need to fix this problem ASAP!


    • Ida, have you tried using this generic GCM one with Urban Airship? As long as UA supports GCM and you have set up the plugin code with your GCM id, I don’t see why it shouldn’t work. I have not tried this myself, but as long as UA is sending thru GCM your app should receive the message using this plugin. Let me know how it goes, or if it needs further tweaks and I’m sure I can help you out with that.


  9. Yudhajit Nag says:

    Excellent. Thanks.

  10. gianvi says:

    hi, i have this problem: (ON LOGCAT):

    – GCMRegistrar: Registering app com.cordova2.gcm of senders “XXX”
    – GCMPlugin:execute: GCMRegistrar.register called
    – GCMBroadcastReceiver: onReceive: com.google.android.c2dm.intent.REGISTRATION
    – GCMBroadcastReceiver: GCM IntentService class: com.cordova2.gcm.GCMIntentService
    – GCMBaseIntentService: Acquiring wakelock
    – GCMBaseIntentService: handleRegistration: registrationId = null, error = SERVICE_NOT_AVAILABLE, unregistered = null
    – GCMBaseIntentService: Registration error: SERVICE_NOT_AVAILABLE

    thanks a loto for the tutorial…is perfect!…but can explain me this error??

  11. Tahir Alvi says:

    Hi Holy,

    A great article over PhoneGap, is your speach avilable in form of video or audio ?


    Tahir Alvi
    Flex Developer.

  12. David says:

    We are trying to figure out how to send and email to an app engine GCM system and then send the body text string to our BizTexter application.

    Any ideas?

  13. roy says:

    Hi holly,

    Great article, this really save me more time. Thank you very much.
    I have two question now.
    First, if I use node-gcm to send message, how to send chinese, all chinese is garbled.
    Secnd, if I use .net to send message, there always
    has error with “401 unauthorized”.I am using the method as http://www.codeproject.com/Articles/339162/Android-push-notification-implementation-using-ASP .
    Thanks again.

  14. Bob says:

    Hi Holy,

    I have a question. Why I get e.regid different every time.
    I am confused.

  15. Bob says:

    Hi holly,
    I have a new question, due to the C2DM may refresh this registration ID periodically. How to refresh that timely.

  16. James says:

    When will you be doing a tutorial for the pushwoosh plugin for android? I tried following their directions but I’m confused on a few things (still new at this).

  17. Rushabh says:

    hi.. gr8 work..!!!
    can u provide server side script for pushing d notification?.. not able to follow node.js

  18. Hansen says:

    I’m a little lost here. I have downloaded GCM Cordova Plugin and got it running.

    On my webserver, I have followed the server instructions from here:


    I have added a few lines in CORDOVA_GCM_script.js to send e-mail, name and regId to my webserver.

    The phone is receiving regID from google, and everything look well, until I try to send a message from my server.

    App is crashing and my log says:
    12-06 20:58:34.718: E/AndroidRuntime(2479): FATAL EXCEPTION: IntentService[GCMIntentService-GCMIntentService-2]
    12-06 20:58:34.718: E/AndroidRuntime(2479): java.lang.NullPointerException: println needs a message
    12-06 20:58:34.718: E/AndroidRuntime(2479): at android.util.Log.println_native(Native Method)
    12-06 20:58:34.718: E/AndroidRuntime(2479): at android.util.Log.v(Log.java:117)
    12-06 20:58:34.718: E/AndroidRuntime(2479): at com.cordova2.gcm.GCMIntentService.onMessage(GCMIntentService.java:63)
    12-06 20:58:34.718: E/AndroidRuntime(2479): at com.google.android.gcm.GCMBaseIntentService.onHandleIntent(GCMBaseIntentService.java:179)
    12-06 20:58:34.718: E/AndroidRuntime(2479): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
    12-06 20:58:34.718: E/AndroidRuntime(2479): at android.os.Handler.dispatchMessage(Handler.java:99)
    12-06 20:58:34.718: E/AndroidRuntime(2479): at android.os.Looper.loop(Looper.java:137)
    12-06 20:58:34.718: E/AndroidRuntime(2479): at android.os.HandlerThread.run(HandlerThread.java:60)

    and next error:
    12-06 20:58:37.238: E/ActivityThread(2479): Activity com.cordova2.gcm.MainActivity has leaked IntentReceiver com.google.android.gcm.GCMBroadcastReceiver@40de3410 that was originally registered here. Are you missing a call to unregisterReceiver()?
    12-06 20:58:37.238: E/ActivityThread(2479): android.app.IntentReceiverLeaked: Activity com.cordova2.gcm.MainActivity has leaked IntentReceiver com.google.android.gcm.GCMBroadcastReceiver@40de3410 that was originally registered here. Are you missing a call to unregisterReceiver()?
    12-06 20:58:37.238: E/ActivityThread(2479): at android.app.LoadedApk$ReceiverDispatcher.(LoadedApk.java:795)
    12-06 20:58:37.238: E/ActivityThread(2479): at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:596)
    12-06 20:58:37.238: E/ActivityThread(2479): at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1316)
    12-06 20:58:37.238: E/ActivityThread(2479): at android.app.ContextImpl.registerReceiver(ContextImpl.java:1296)
    12-06 20:58:37.238: E/ActivityThread(2479): at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:430)
    12-06 20:58:37.238: E/ActivityThread(2479): at com.google.android.gcm.GCMRegistrar.setRetryBroadcastReceiver(GCMRegistrar.java:276)
    12-06 20:58:37.238: E/ActivityThread(2479): at com.google.android.gcm.GCMRegistrar.register(GCMRegistrar.java:202)
    12-06 20:58:37.238: E/ActivityThread(2479): at com.plugin.GCM.GCMPlugin.execute(GCMPlugin.java:62)
    12-06 20:58:37.238: E/ActivityThread(2479): at org.apache.cordova.api.PluginManager$1.run(PluginManager.java:192)
    12-06 20:58:37.238: E/ActivityThread(2479): at java.lang.Thread.run(Thread.java:856)

    I can see that I’m not the only with this error, but have not been able to find a solution.

    Any help would be appreciated 🙂

  19. Kent says:

    I want to ask how to implement when apps is running still get the notification?

  20. Pankaj says:


    Its a nice explanation. I have implemented it as well but i am facing an issue, not sure if its a trivial one. following are the details:
    1) I have an application html5 based using jquery mobile . i have multiple pages like say 1.html 2.html 3.html etc.
    2) I packaged them all with cordova and set load 1.html as the starting page in the main activity ( i have this only activity)
    3) implemented GCM plugin for cordova successfully.
    4) implemeted statusbar notification plugin for cordova successfully.
    5) i am receiving the message and displaying it successfully .
    6) Issue: when i tap on notification its launching a new instance of my application starting from 1.html, how do i direct click to my existing instance or more so to say 3.html.

    i hope i made myself clear enough.


  21. Ajar says:

    Hi everyone
    For those of you coming back to this blog hoping to get some flash love
    If you feel like writing your apps & games for the mobile in Flash/Flex AS3, you can find a whole market of native extensions, among them also native push notifications:



  22. Priyank says:

    Hi, I am new in phonegap.
    I can’t understand anything in phonegap.
    please anybody tell me what is it, how to setup/configure, and how it works.

    please reply immediate

  23. Radu says:

    I have edited the CORDOVA_GCM_script.js file to use my GCM sender/project id in the register function. It seems like the EVENT callback function isn’t called (Last message () is the one appended by the SUCCESS callback function). Is there a common problem that generates this?

    When I tried to adjust my own project adding packages and making all adjustment I got the same problem. More than this, when I was calling the unregister function I was getting an error regarding my main activity which “has leaked IntentReceiver com.google.android.gcm.GCMBroadcastReceiver..” – this may be from tha fact that I havent named that class as suggested.

    I’d be very grateful if you would give me some hints.

    With admiration
    for your skills
    and experience,


  24. luongbeta says:

    It’s very nice. Thanks!

  25. Jorge says:

    Hi Holly,

    First of all, congratulations for such a nice tutorial, I followed every step and successfully added notification support to my existing phonegap-android application.
    I only have one question and hope you can help me a little bit, is there a way to run a specific javascript function when the user clicks on the notification in status bar?

  26. zoni says:


    i have an issue , we i call my service it gave me “MismatchSenderId”, i have tried but could not figure it out …
    anyone has any idea why it is so … ???

  27. Schnasi says:

    Hi Holly,

    do you know how i can change the google gcm server url to a local gcm server url?
    Because i would like to register my device on my own gcm server.

    Like this http://androidv5.wordpress.com/2012/08/15/how-to-implement-google-cloud-messaging/ example but with the gcm phonegap plugin.



  28. Venkatesh says:

    Hai guys,

    Anybody knows how to fix the tab bar to the bottom using phonegap in android

    I want the solution for this problem its very urgent

  29. Nando says:


    I downloaded the plugin:


    And I’ve tried on my Android CORDOVA_GCM_script.js changing the method for my id:

    window.GCM.register(“project_id”, “GCM_Event”, GCM_Success, GCM_Fail );

    But I get the error:

    Cannot call method ‘register’ of undefined at file:///android_asset/www/CORDOVA_GCM_script.js

    Anyone else has happened?


  30. dele says:

    I’m getting deprecation warnings on the lines:
    Notification notif = new Notification(android.R.drawable.btn_star_big_on, message, System.currentTimeMillis() );


    notif.setLatestEventInfo(context, title, message, contentIntent);

  31. Please note I will be hosting two webinars on push notifications for Android and iOS in February via TechLive. The webinar for Apple Push Notifications handling in a PhoneGap application will be held on Feb 8th and the Android push notification with PhoneGap session on Feb 22nd so plan to attend or view the recordings that will be posted after.

  32. Martin Thorp says:

    Thanks for the great tutorial. I have everything functioning except for the sending of the message after a notification. I have added your suggested code to the onMessage method of the GCMIntentService class and this works: the notification shows and the application is openend, but, the message event is then not delivered to the application. Do I need to add the sendJavascript call to the notification somewhere?

    Thanks again for a great tutorial and for reading.

    • Martin Thorp says:

      Ahh I see that the message is delivered when the application is already open when the notification is received. So I presume I need to move the messaging code to the MainActivity class and react to an intent or register an event handler maybe.

      • Martin Thorp says:

        In the end I only accept notifications when the application is paused and I have overridden the back button to sendToBack as opposed to close the application. Then I have changed the plugin to accept a new intent and then use start activity on that new intent to send it once the application has come out of pause. Works fine. The main thing is keeping the app on pause.

  33. dele says:

    please is there a way to make the notification launch a specific page of the app instead of the default.

  34. weward says:

    I have the same problem as Nando.
    I downloaded the plugin:


    And I’ve tried on my Android CORDOVA_GCM_script.js changing the method for my id:

    window.GCM.register(“project_id”, “GCM_Event”, GCM_Success, GCM_Fail );

    But I get the error:

    Cannot call method ‘register’ of undefined at file:///android_asset/www/CORDOVA_GCM_script.js

    what is causing this problem?
    Pls help us. TIA

  35. Alma Martinez says:

    Hi Holly,
    Great tutorial!! I tried all kind of solutions for 2 days until I found your post. I followed it and…finally the GCM notifications worked in my app!!!
    Thank you very much,

  36. madcaplaughs says:

    Hi Holly,

    Awesome Tutorial.

    I have one problem though, I have got everything to work but my app is not receiving any messages.

    I have used cURL in PHP to send a message to GCM which works fine as it returns multicast_id, message_id and success:1 but the app does not receive it neither does the eclipse log.

    Can you tell me why?

  37. Jeanette says:

    I have the same problem:

    Cannot call method ‘register’ of undefined at file:///android_asset/www/CORDOVA_GCM_script.js

  38. weward says:

    hi holly,

    do you have another method to send push messages aside from using node-gcm/node.js

    I’ve been trying to use the php script from the androidhive site(android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql)
    to send a push message. but can’t understand why it doesnt work.
    Could you help me(or us) with sending push messages using php. thanks.

    • madcaplaughs says:

      I am using this PHP script and it works fine:

      ‘data’ => array( “message” => $message ) /*Make sure that message is the key you are using in GCMIntentService.java onMessage() -> extras.getString(“message”);*/

      $headers = array(
      ‘Authorization: key=’ . $apiKey,
      ‘Content-Type: application/json’

      // Open connection
      $ch = curl_init();

      // Set the url, number of POST vars, POST data
      curl_setopt( $ch, CURLOPT_URL, $url );

      curl_setopt( $ch, CURLOPT_POST, true );
      curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
      curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
      curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
      curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );

      // Execute post
      $result = curl_exec($ch);

      // Close connection

      // Echo success or failure
      echo $result;

  39. weward says:

    is it possible to support both APNs and GCM push notification in one server?
    If i have an app that would cater both OSes(chat app for example). Is it possible to have a working push notification for both in one server? how would my server know that it should push using apns instead of gcm or teh other way around? thanks again.

  40. Harsha says:

    Hi Your Blog is Very Helpful to all.

    And Now Am Trying to develop an Android Application Using GCM for push notifications.Please provide Step by Step Procedure for how can i develop using GCM in Android GoogleAPI.

  41. vinay says:

    hie iam newbiee to android..iam developing app which send notifications to device..myquestion is how to implement server side code..my client application is in java..and my backend is .net.can anyone provie how to write sever side code in java or .net and when i get regid i should pasthat to server..i tried many days but cant figure out how to do it.soplz help me in doing dat./.i will be thankful to u.someone gime the snippet code for server side implementation..thank you

  42. Alex says:


    I followed the tutorial proposed by mark and tested his project. I had the same problem as Nando but solved it as madcaplaughs described in a previous comment. However, now the last message I receive is the one from GCM_Success method, but the GCM_Event method is never getting called and so I don’t have any regid for my device. I don’t understand from where does this problem come and how can it be solved. Many thanks, Alex.

  43. Vinod says:

    The tutorial is nice and I could successfully get the reg id back from Google.
    I am using server side script from http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/
    But when I send message from server the app crashes and please find my log here

    02-14 17:36:13.684: E/AndroidRuntime(377): FATAL EXCEPTION: IntentService[GCMIntentService-GCMIntentService-2]
    02-14 17:36:13.684: E/AndroidRuntime(377): java.lang.NullPointerException: println needs a message
    02-14 17:36:13.684: E/AndroidRuntime(377): at android.util.Log.println_native(Native Method)
    02-14 17:36:13.684: E/AndroidRuntime(377): at android.util.Log.v(Log.java:116)
    02-14 17:36:13.684: E/AndroidRuntime(377): at com.cordova2.gcm.GCMIntentService.onMessage(GCMIntentService.java:63)
    02-14 17:36:13.684: E/AndroidRuntime(377): at com.google.android.gcm.GCMBaseIntentService.onHandleIntent(GCMBaseIntentService.java:179)
    02-14 17:36:13.684: E/AndroidRuntime(377): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:59)
    02-14 17:36:13.684: E/AndroidRuntime(377): at android.os.Handler.dispatchMessage(Handler.java:99)
    02-14 17:36:13.684: E/AndroidRuntime(377): at android.os.Looper.loop(Looper.java:130)
    02-14 17:36:13.684: E/AndroidRuntime(377): at android.os.HandlerThread.run(HandlerThread.java:60)
    02-14 17:36:13.757: D/DroidGap(377): Paused the application!

    what may be the reasons for this issue. Please advice.

  44. Rash says:

    in step 3 sender_id is hard coded value. can i generate dynamically? any way to do so…

  45. Andrew says:

    Hello Holly,

    The article is great.
    But I have a little problem.

    In case when application isn’t loaded. I recieved notification and clicked on it. Application is shown but I haven’t message text in console (like “MESSAGE->MSG: You turn!!!!”).

    Could you please explain what should I do to see this text.

  46. Francisco says:

    Hi Holly. Great article i’m impressed with this, but i have the same problem that Andrew (up message).

    I have registered my google API and i have configured the Pushwoosh with the API KEY of google Cloud Messaging.

    Any help? Please? Greetings from Chile!

  47. Vasilis says:

    Hey Holly ,
    very nice tutorial indeed. I have a question though. If we need to get the device UUID how could we do that to send it to the server? Can it be done through phonegap or it needs native code?

  48. Hi Your Blog is Very Helpful to all.

    And Now Am Trying to develop an Android Application Using GCM for push notifications.Please provide Step by Step Procedure for how can i develop using GCM in Android GoogleAPI.

  49. twj84 says:

    Hi Holly,
    I have tried as the guide. But when I run, the issue is triggerd as below. Could you give some advice?

    03-19 09:27:04.610: E/InputDispatcher(229): channel ‘2b4181c8 com.phonegap.helloworld/com.phonegap.helloworld.MainActivity (server)’ ~ Consumer closed input channel or an error occurred. events=0x8
    03-19 09:27:04.610: E/InputDispatcher(229): channel ‘2b4181c8 com.phonegap.helloworld/com.phonegap.helloworld.MainActivity (server)’ ~ Channel is unrecoverably broken and will be disposed!
    03-19 09:33:23.990: E/MyLog(14401): ZY>>LOGD=false
    03-19 09:46:29.940: E/MyLog(14440): ZY>>LOGD=false
    03-19 09:58:06.140: E/wpa_supplicant(12584): Ongoing Scan action…
    03-19 10:00:42.490: E/MyLog(14550): ZY>>LOGD=false
    03-19 10:06:15.510: E/MyLog(14565): ZY>>LOGD=false

    • Vasilis says:

      @twj84 , where do u get this problem ? When you are trying from ur server to send a push?

      • twj84 says:

        @Vasilis , after debug, the issue is triggered at below:
        window.plugins.GCM.register(“283007905633”, “GCM_Event”, GCM_Success, GCM_Fail );

        I just follow the guide to do that. It seems cannot register.

  50. Vasilis says:

    Are you using the simulator? You should use an actual device for this.

    • twj84 says:

      I am using the actual device, sony Xperia Play

      • Vasilis says:

        Actually there are really many things that could have gone wrong , one being using the simulator. What you can do , is write one by one the errors on google , eg “Channel is unrecoverably broken and will be disposed!” and see what other people have reported especially on stackoverflow and how they solved it. I found at least 5 different things , on why this/these errors might occur. Most probably you did something wrong on following the tutorial , or you forgot to add something on your XML file. If you run the sample project do you get the same error or it works? Remember that you should use your own data to register and not the ones given in the sample.

  51. Cesar says:

    This worked great. You’re awesome.

  52. meme says:

    hello there
    could anyone send the project for me

  53. Akira2788 says:

    Thank you so much for the tutorial , it works , but it is possible to notify with sound and it is possible in android to have a icon counter if i have more than one notification?

  54. wajihurrehman says:

    hi every one please please any one who can implemented this and getting registered id because i have set up and follow documentation but i am not getting reg id .

    i also replaced my updated project number from google as well enabled gCM for Android.

    Output after follow this documention on emulator.
    Cordova google cloud messaging pugin demo
    device ready event recieved
    Calling GCMRegistar.registar
    register our sender id with google

    i will be really thankful to you please if u have just 15 mintes can u check my all setting on teamviwer what ever time will you have just i will online please it’s urgent i am trying more than 25 days but still not succed waiting for your good reply.

  55. wajihurrehman says:

    any one can send me project at wajihurrehman90@hotmail.com

  56. wajihurrehman says:

    Here is catlog Output on android but u can see not getting register ID even not trigering GCM Event in used window.plugins.GCM.register(“my_app_id”, “GCM_Event”, GCM_Success, GCM_Fail );

    Please any one tell me what’s the prolem where i am wrong.

    11-09 20:17:06.180: I/CordovaLog(1245): Changing log level to DEBUG(3)
    11-09 20:17:06.190: I/CordovaLog(1245): Found preference for useBrowserHistory=true
    11-09 20:17:06.190: D/CordovaLog(1245): Found preference for useBrowserHistory=true
    11-09 20:17:06.190: I/CordovaLog(1245): Found preference for exit-on-suspend=false
    11-09 20:17:06.190: D/CordovaLog(1245): Found preference for exit-on-suspend=false
    11-09 20:17:06.220: D/DroidGap(1245): DroidGap.onCreate()
    11-09 20:17:06.550: D/CordovaWebView(1245): CordovaWebView is running on device made by: unknown
    11-09 20:17:06.570: D/JsMessageQueue(1245): Set native->JS mode to 2
    11-09 20:17:06.603: D/DroidGap(1245): DroidGap.init()
    11-09 20:17:06.640: D/CordovaWebView(1245): >>> loadUrl(file:///android_asset/www/index.html)
    11-09 20:17:06.654: D/PluginManager(1245): init()
    11-09 20:17:06.700: D/CordovaWebView(1245): >>> loadUrlNow()
    11-09 20:17:06.700: D/DroidGap(1245): Resuming the App
    11-09 20:17:06.780: D/SoftKeyboardDetect(1245): Ignore this event
    11-09 20:17:06.900: I/Choreographer(1245): Skipped 125 frames! The application may be doing too much work on its main thread.
    11-09 20:17:06.990: D/gralloc_goldfish(1245): Emulator without GPU emulation detected.
    11-09 20:17:07.271: I/Choreographer(1245): Skipped 190 frames! The application may be doing too much work on its main thread.
    11-09 20:17:07.271: D/SoftKeyboardDetect(1245): Ignore this event
    11-09 20:17:07.400: D/DroidGap(1245): onMessage(onPageStarted,file:///android_asset/www/index.html)
    11-09 20:17:10.820: D/chromium(1245): Unknown chromium error: -6
    11-09 20:17:11.450: D/dalvikvm(1245): GC_FOR_ALLOC freed 301K, 13% free 2718K/3100K, paused 38ms, total 41ms
    11-09 20:17:11.460: D/CordovaNetworkManager(1245): Connection Type: 3g
    11-09 20:17:11.460: D/DroidGap(1245): onMessage(networkconnection,3g)
    11-09 20:17:11.470: D/CordovaNetworkManager(1245): Connection Type: 3g
    11-09 20:17:11.492: D/DroidGap(1245): onMessage(spinner,stop)
    11-09 20:17:11.570: D/Cordova(1245): onPageFinished(file:///android_asset/www/index.html)
    11-09 20:17:11.570: D/DroidGap(1245): onMessage(onPageFinished,file:///android_asset/www/index.html)
    11-09 20:17:11.660: V/GCMPlugin:execute(1245): action=register
    11-09 20:17:11.670: V/GCMPlugin:execute(1245): data=[{“senderID”:”XXXXXXXXXX”,”ecb”:”GCM_Event”}]
    11-09 20:17:11.690: V/GCMPlugin:execute(1245): jo={“senderID”:”XXXXXXXXXX”,”ecb”:”GCM_Event”}
    11-09 20:17:11.690: V/GCMPlugin:execute(1245): ECB=GCM_Event senderID=XXXXXXXXXX
    11-09 20:17:11.700: V/GCMRegistrar(1245): Registering receiver
    11-09 20:17:11.710: D/GCMRegistrar(1245): resetting backoff for org.apache.cordova.example
    11-09 20:17:11.740: V/GCMRegistrar(1245): Registering app org.apache.cordova.example of senders XXXXXXXXXX
    11-09 20:17:11.760: V/GCMPlugin:execute(1245): GCMRegistrar.register called
    11-09 20:17:11.820: D/TilesManager(1245): Starting TG #0, 0x2a234580
    11-09 20:17:12.832: I/Choreographer(1245): Skipped 66 frames! The application may be doing too much work on its main thread.

  57. abdul says:

    is this plugin support phonegap 1.2 version?.

  58. Suresh Raja says:


    Getting error as , Undefined “GCM” in the below line (due to which I’m unable to get registration ID)

    window.plugins.GCM.register(“661553999684”, “GCM_Event”, GCM_Success, GCM_Fail );

  59. Anas says:

    How can I redirect to a particular (.html) page after a notification is clicked in the status bar in Android (I want this to accomplish in iOS too, but this topic is for Android).
    Any help would be greatly appreciated.

  60. Muhannad says:


    Thanks for the tutorial, but what Cordova version were you using back then? I’m using 3.4 & this GCM plugin keeps crashing my app, below is some plumping i did:

    1)JS register function was not available on (window.GCM) but instead on window.plugins.GCM.
    2)the GCMPlugin.js seemed incomplete! in GCM.prototype.register the author calls Cordova.exec & in unregister calls cordova.exec (C, c) I had to alter it for it to work.
    3)following their guideline to alter AndroidManifest.xml & res/xml/config.xml, the latter gets overwritten every time you build the app & the line () disappears.

    4)I had to move the implementation into a plugin package (src,www,plugin.xml) & install it with cordova plugins add… , now the plugin is persistent in res/xml/config & i am no longer getting ‘unknown plugin errors’ in logcat but still the app is crashing with a verbose log below:




    the generated res/xml/config


    please note this is barely a hello world app with device, geolocation & GCM plugins, problems started after adding the latter.

    any idea? this is my first experience with cordova & my excitement is starting to fade out…

    Thank you.

Leave a Reply