Wednesday, July 4, 2012

Google cloud Messaging (GCM) tutorial

At the Google IO 2012, the beta version of Android push notifications system called C2DM was replaced by Google Cloud Messaging (GCM). GCM has many new features over the existing system. Refer to this document for details of the differences and details about migrating your existing systems from C2DM to GCM.

To get started, download the Extras > Google Cloud Messaging for Android Library from the Android SDK.This library provides the jars to simplify the development on both the server side and client side.

From the Google API console page, create a new project and generate the API key. Refer this page for complete details.

Client Application

Create a new android project and add the GCM.jar to its buildpath.Generate the AndroidManifest.xml file as per the document. You can also verify that all the required parameters have been set in the manifest file by calling this function:
Create a new activity and add the following code to register. replace the SENDER_ID with the 12 digit project Id from the URL.
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
  GCMRegistrar.register(this, SENDER_ID);
} else {
  Log.v(TAG, "Already registered");

Once the app is created, run it on the android device and note the registrationId from the logs. Make sure that the device is having Android Market/Play Store installed and signed in using a Google Account. The code might not run on emulators.
Add a service to the project which would extend the GCMBaseIntentService and implement what needs to be done when on registration, de-registration, message receipt etc. On receiving a message, the data sent from server is in the form of an intent which can be resolved as :

protected void onMessage(Context arg0, Intent arg1) {
// Get the data from intent and send to notificaion bar
generateNotification(arg0, arg1.getStringExtra("message"));
In the generateNotification function, add the code that you need to do on receiving a message.In this example, I display the text in the notification bar.

Server Application
To test the push notifications, create a simple java project with a main function. Add the gcm-server.jar from the Android SDK extras folder to its build path.

Use the below code to send the notifications:

Sender sender = new Sender("AIzaXXXXXXXXXXXXXXXXXXXXXXXXX");
Message message = new Message.Builder().build();
Result result = sender.send(message,"device_token", 1);

To add some payload data into the notification, create the message using the below code.This message is sent as an intent which can be resolved at the client end.
Message message = new Message.Builder()
     "this text will be seen in notification bar!!")
To multicast a message, use an List of device tokes. Use a MulticastResult Object in this case instead of the Result object as done earlier:
devicesList = new ArrayList();


MulticastResult result = sender.send(message, devicesList, 1);
sender.send(message, devicesList, 1);

Google provides the sample apps in the SDK by default, you may download a very basic version of them containing only the code discussed in this tutorial from here.
The same application is also available on play store here.

Few points to be taken care of:
1. If you use EmailId as the SENDER_ID, then you are actually registering for C2DM and not GCM. The notifications would not be received using this code although you. would be able to fetch the registrationId
2. In the above code, on receiving a notification,only a logcat entry is seen. You may edit the same to show the text on notification bar or perform any other action by editing the class which implements GCMBaseIntentService .
3.While uploading the application to Play Store, Navigate to "Services and API" section and Link the sender IDs to ensure proper functioning.

1. Multicast Messages
2.Payload data from server
3.Receive Payload data and display as notificatoin