Tuesday, May 15, 2012

Android Cloud to Device Messaging (C2DM)

It is easy to do "pull" from Android (or anything). Just use an http request. What about "push"? How do you send a message to your phone? There is the Cloud-to-Device-Messaging API. (Sure you can have a thread to periodically listen for messages intended for your phone too).

The link above is nice. It tells you the nuts and bolts but alas, where are the simple examples? There are complex over bloated examples in there. I want something simpler and to the point!

This gentleman wrote a lot of great examples for a lot of things: Lars Vogella's C2DM Tutorial.

There are many examples out there too. But they want to use the Unix curl command. I am in Windoze, Ok?

Everyone just have to put chunks of code but not runnable simple code, and even if you follow exactly there are got-chas.

Here are the steps.
1) First, you'll need a google account and sign up for C2DM, and provide your package name like com.mycompany.myapp

2) In your app, set up the manifest with all sorts of permissions as shown in the google c2dm link. You need a C2DMReceiver class that handles registration and messages sent to you.

3) To send message, you need 3 things.
1. Register on the phone to get a registration String from the C2DM Handler.

The 4 lines seen in google c2dm link works wonders. You need to somehow have the phone communicate this back to the sender application. (Vogelle send this to himself with http Post) I just System.out.println and captured it. You can probably send a email to yourself or something (silently).

2. An authorization ID from google ClientLogin given your google login/password, the form action is https://www.google.com/accounts/ClientLogin

Account Type:

See that Auth ID? copy it.

3. The message itself, of course

4) Now you can write a separate program to send message to your phone with the 2 IDs above and the message. Vogelle's MessageUtil work well. I added this method, and run the class as a command line app.

 public static void main(String args[]) {
  String auth_token="...";    // you supply yours here (step 3.1)
  String registrationId="..."; // you supply yours here (step 3.2)

  String message="something";
  if (args.length>0) {
  int status=0;
  try {
  status = sendMessage(auth_token,registrationId,message);
  } catch (Exception e) {
  System.out.println("Done sending, status="+status);
5. Final note, if you see an error in logcat saying something like the following:
ERROR/TalkProvider(232): java.lang.IllegalArgumentException: the bind value at index 2 is null
Turn off your google talk on your phone. Apparently google is using google talk as the way to send message to your phone.