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.
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:
The steps for setting up push notifications in your Android application are:
https://code.google.com/apis/console/?pli=1#project:824841663942
window.GCM.register("your_sender_id", "GCM_Event", GCM_Success, GCM_Fail );
window.GCM.register("824841663942", "GCM_Event", GCM_Success, GCM_Fail );
If you need more information about GCM project creation, specific steps can be found here.
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:
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.
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);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
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;
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:

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.addData('msgcnt','1');
message.collapseKey = 'demo';
message.delayWhileIdle = true;
message.timeToLive = 3;
// At least one token is required - each app will register a different token
registrationIds.push('APA91bFobAwN7P3Okxy2al8RI12VcJFUS-giXWTOoWXIObtSPOE1h7FuH1VPLBPgshDI_Fp7aIYVET-ssvGUErlWYA0cKPGhoXT1daqyDsEfem9ZtgZNRhQFv7kLCIVSigYlpMluToPiSHSsFSEdtCDfKoOZqNPgfs');
/**
* Parameters: message-literal, registrationIds-array, No. of retries, callback-function
*/
sender.send(message, registrationIds, 4, function (result) {
console.log(result);
});
/** Use the following line if you want to send the message without retries
sender.sendNoRetry(message, registrationIds, function (result) { console.log(result); });
**/
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:
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.
hi,
just what i need in my app.
will try to implement notification next week!
nice explanation.to use thankss
Hi,
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.
pls share your php script for push notification. Mine doesnt work.
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", true);
xmlhttp.send("token="+token+"&message=pushnotificationtester");
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
!!
Holly
Thanks, work great
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.
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.
TIA.
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
Thank you Holly,
After a search for a Cordova Android GCM plugin, your tutorial confirms our findings of Mark Nutters plugin.
(Your addition of the native Java status bar code fits perfectly!)
Your tutorial puts the dots on the i, thank you for that…
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,
Saša
Hey Holly
Will you be posting any Flex/AS3 related content on this blog, or did you switch entirely to HTML5 related materials?
Cheers
Yariv
Does this CGM Cordova Plugin work with UrbanAirship? I’m developing a project with PhoneGap Android and I need to use UrbanAirship.
Hi Ida,
There’s actually a specific plugin available for cordova to work with Urban Airship on Android here: https://github.com/urbanairship/phonegap-ua-push. There’s also this link if you need plugins for other platforms as well.
Hope that helps!
Holly
Hi,
Thanks for the links! but the first linke(Phonegap-ua-push) doesn’t work with GCM. I need a GCM plugin for Urban Airship.
/Ida
Anybody else has any idea?
Need to fix this problem ASAP!
/Ida
Anybody else has any idea?
Need to fix this problem ASAP!
/Ida
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.
Thanks!
Holly
Excellent. Thanks.
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??
Hi Holy,
A great article over PhoneGap, is your speach avilable in form of video or audio ?
Thanks
Tahir Alvi
Flex Developer.
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?
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.
Hi holly,
I have resolved that. Please ignore this question.
Thank you.
Hi Holy,
I have a question. Why I get e.regid different every time.
I am confused.
Hi holly,
I have a new question, due to the C2DM may refresh this registration ID periodically. How to refresh that timely.
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).
Hi James, I’m working on PushWoosh this week so keep checking back
! Holly
hi.. gr8 work..!!!
can u provide server side script for pushing d notification?.. not able to follow node.js
[...] recently posted regarding the use of Push Notifications on both iOS and Android with PhoneGap. Both of those addressed sending push notifications from a general 3rd party server [...]
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:
http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/
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
Hi Hansen,
Have you managed to fix your issue as I am having the same problem.
Thanks
The same problem!
Help!
Hi Hansen,
I do the same thing you follow, server code from http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/
I got the same error, do you have find the solution? If so please help me.
Regards,
Vinod
I got it fixed. I used server side script from http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/ Need to edit the line //$message = array(“price” => $message);, change “price” to “message” , because on java file the variable name is “message”. Now it works for me . Pasting the code here (commented the problem occurring line)
if (isset($_GET["regId"]) && isset($_GET["message"])) {
$regId = $_GET["regId"];
$message = $_GET["message"];
include_once ‘./GCM.php’;
$gcm = new GCM();
$registatoin_ids = array($regId);
//$message = array(“price” => $message);
$message = array(“message” => $message);
$result = $gcm->send_notification($registatoin_ids, $message);
echo $result;
}
I had the same problem, it solved when I added:
“”
to the manifest file.
I want to ask how to implement when apps is running still get the notification?
Hello,
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.
Thanks,
Pankaj
我现在用html5+ jquery 做这个推送通知,不知道怎么弄,能加下QQ嘛 QQ:617628097
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:
http://www.scoop.it/t/flash-interactive/p/1423876452/tools-milkman-games
http://www.scoop.it/t/flash-interactive/p/1454838169/community-of-native-extensions-for-adobe-airnative-extensions-for-adobe-air
enjoy
Ajar
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
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,
Radu.
It’s very nice. Thanks!
[...] have followed this tutorial in order to test GCM with [...]
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?
Thanks
hi
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 … ???
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.
Thanks
Regards
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
Hello.
I downloaded the plugin:
https://github.com/marknutter/GCM-Cordova
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?
Thanks!!
change it to:
window.plugins.GCM.register(“project_id”, “GCM_Event”, GCM_Success, GCM_Fail );
Thank you very much! I had the same problem and I have managed fix it by adding “.plugins”
I’m getting deprecation warnings on the lines:
Notification notif = new Notification(android.R.drawable.btn_star_big_on, message, System.currentTimeMillis() );
and:
notif.setLatestEventInfo(context, title, message, contentIntent);
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.
Hello.
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.
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.
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.
please is there a way to make the notification launch a specific page of the app instead of the default.
[...] sender id in the index.js file. Also, see my previous tutorials on push notifications for iOS and Android to get some sample code in PHP or node.js to send a push notification quickly for testing so you [...]
I have the same problem as Nando.
I downloaded the plugin:
https://github.com/marknutter/GCM-Cordova
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
change it to:
window.plugins.GCM.register(“project_id”, “GCM_Event”, GCM_Success, GCM_Fail );
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,
Alma
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?
I have the same problem:
Cannot call method ‘register’ of undefined at file:///android_asset/www/CORDOVA_GCM_script.js
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.
I am using this PHP script and it works fine:
$registrationIDs,
‘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
curl_close($ch);
// Echo success or failure
echo $result;
The code did not come completely above…
goto: http://pastebin.com/7cvi9ReM
thanks! you are a life saver!
the PHP script worked.My script didnt have that “message” on the ‘data’ part. thanks.
But this isnt cross comatible with other mobile os’es like ios right? do you have an idea on how could I make it cross compatible? thanks again.
well you are using GCM (Google Cloud Messaging) for Android Push Notifications. For iOS you need to use APNs(Apple Push Notifications) : http://devgirl.org/2012/10/19/tutorial-apple-push-notifications-with-phonegap-part-1/
So i don’t know how to implement your script. Can you go more specific the explanation, i’m stuck in the “Registered” message.
Please help me, thanks.
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.
If you are using phonegap then take a look at http://docs.phonegap.com/en/1.0.0/phonegap_device_device.md.html.
Using device.platform you can understand whether the user is using Android or iOS or anything else. Accordingly you code your back-end to determine how to send the push notification.
You’ve been a great help. Thank you so much!
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.
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
Hello,
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.
Hi,
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.
Regards,
Vinod
in step 3 sender_id is hard coded value. can i generate dynamically? any way to do so…
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.
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!
[...] To send the message to my application, I use node.js with this script, just as explained by Holly Schinsky on this post: [...]
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?
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.
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=0×8
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
@twj84 , where do u get this problem ? When you are trying from ur server to send a push?
@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.
Are you using the simulator? You should use an actual device for this.
I am using the actual device, sony Xperia Play
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.
The issue is fixed. The reason is that I had missed the setup for GCM in config.xml as below:
Thanks Vasilis’ advice
Happy that i could help
This worked great. You’re awesome.