Requirements
 
Prerequisite knowledge
This article requires at least an intermediate level of PhoneGap development experience.
 
User level
All
 
 
Required products

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.

Google Cloud Messaging
 
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:
● 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 wakes 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.
● GCM 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.

Setting up push notifications
 
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:
https://code.google.com/apis/console/?pli=1#project:824841663942
Don't forget to change the following to use your GCM project id (from the step above) so that the following code
window.GCM.register("[your_sender_id]", "GCM_Event", GCM_Success, GCM_Fail );
contains your sender ID:
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. For example, you might display a popup alert or a status bar notification.

Note: The plugin handles registering with GCM and has methods for receiving a message, however it does not actually provide the response to 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 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.
 
1. Choose File | New | Project.
2. Select “Android Project from Existing Code.”
 
Select “Android Project from Existing Code”.
Figure 1. Select “Android Project from Existing Code”.
 

Running the sample application
 
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 see a message containing the registration token id.
Figure 2. You see a message containing the registration token id.

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:
 
When a message is received, you see additional text displayed.
Figure 3. When a message is received, you see additional text displayed.
 
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.
 

Status bar notification
 
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).
 
Status bar notification when it includes a star icon, vibration and default sound.
Figure 4. Status bar notification when it includes a star icon, vibration and default sound.
 
When you click on the notification, the app opens and shows that a message was in fact received.
 
Clicking on the notification causes app to open and show that a message was received.
Figure 5. Clicking on the notification causes app to open and show that a message was 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.
 

Sending a message with node-gcm
 
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");
            ....
        }
    }

Collapse key
 
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.
Set the name of the title and message keys explicitly to title and message. Also, note these status bar notifications appear in the expanded list (if not dismissed yet), as in the Figure 7.
Figure 6. Set the name of the title and message keys explicitly to title and message. Also, note these status bar notifications appear in the expanded list (if not dismissed yet), as in the Figure 7.
 
Status bar notifications are shown in the expanded list.
Figure 7. Status bar notifications are shown in the expanded list.
 
Other plugin options
 
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.
 
Where to go from here
 
Below are some related links you may want to check out:
● Cordovapush Project – cross-platform push server based on node-apn and node-gcm
● Urban Airship Push Notification Service – integrates with PhoneGap
 
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.