17 December 2012
This article requires at least an intermediate level of PhoneGap development experience.
All
My last article covered push notifications with PhoneGap on Apple devices. In this article, I cover push notifications with PhoneGap on Android for those developing for this platform. 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, which is similar to Apple's Push Notification Service. Previously they were supported through C2DM (the 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 as there are a lot of details I do not cover in this article. Some points I wanted to highlight from that article are:
The steps for setting up push notifications in your Android application are:
register() function:https://code.google.com/apis/console/?pli=1#project:824841663942window.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.
The PhoneGap plugin includes a sample project already setup to register for push notifications including the AndroidManifest.xml changes and plugin configuration. 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 the existing Android project that you just created above or the sample included in the plugin and start working from there.

When you run the sample code from the plugin, it automatically attempts to register your device. If registration is successful, you see a message containing the registration token id. (See the REGID string 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 obtain a registration id as above, you can write server code. The section below covers how to use Node.JS code to send a message to your application. Alternatively, you can use a service like Urban Airship or PushWoosh to start sending notifications. When a message is received, you see additional text displayed as shown in the screenshot below:

At this point though, the plugin does not do anything. The next section covers how you can add some additional code for showing a status bar notification when the message is received.
Since the plugin simply receives the message—whether your app is running or not—but doesn't do anything with it from there, you have choices for what you do with it. One common requirement is to show a message in the native status bar. On iOS, the process is different and the notification is automatically shown. But on Android you have to explicitly code for it.
One option is to use the Cordova StatusBarNotification plugin along with this one. If you want a faster solution, simply add the native Java code into your GCMIntentService.java onMessage() function, as in the following code:
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, add the following 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 opens and shows that a message was in fact received.

Status bar notifications displays differently depending on the type of device. For example, Android phones typically show them at the top versus at the bottom as shown in my screenshots.
There's a Node.js library for sending notifications through Google Cloud Messaging. It's called node-gcm. Below is the code I used to send my device a message.
Note that I have changed the keys. In the Sender parameter, specify your own 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. If one does not, try the other. Also 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 registers 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); });
**/
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");
....
}
}
According to the Android developer documentation, when you define a collapse key, it only deliver the last notification received with a given collapse key, therefore saving the user from becoming 'over-notified' such as in the case of sports scores for example.


Lastly, I wanted to point out that if you are searching for information about Cordova push notification plugins for Android, you may also come across another plug-in in shader's GitHub here. This plugin is designed to be more specific to using notifications from PushWoosh, which I covered in my blog post, "Easy PhoneGap Push Notifications with Pushwoosh." The plugin's 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. Additionally, I did not have to add the native Java code shown above to show the status bar notification.
Below are some related links you may want to check out:
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.