red orange yellow green blue

C2DM Setup Tutorial

I had to look around for some time to get all my questions answered when trying out C2DM the first time.  I hope that this answers most of the questions that you would have had!  I don’t cover the server side implementation of this, but I can give a brief overview of what to expect with it if needed.


1. First, you need to register over at Google’s signup page.

2.  Once you get a confirmation email back, and the server side is set up, you’re ready to go!



  • -ADMIN_EMAIL is the email address of the account you are publishing apps to the Play Store with.
  • -YOURACTIVITY is the your main Activity class.  If you make TestApp, then it would be TestApp.this
//Cloud to Device Messaging creation, receiving, and handling
//Creation done in onCreate unless you need it done elsewhere

//Must be done in a seperate thread due to networking
//Use AsyncTask once you know this works
new Thread(new Runnable()
    public void run()
        Intent registrationIntent = new Intent("");
        registrationIntent.putExtra("app", PendingIntent.getBroadcast(YOURACTIVITY.this, 0, new Intent(), 0));
        registrationIntent.putExtra("sender", ADMIN_EMAIL);

Next, you need a C2DM Receiver class that extends BroadcastReceiver

public class C2DMReceiver extends BroadcastReceiver {

public final void onReceive(Context context, Intent intent)
 handleRegistration(context, intent);
 else if(intent.getAction().equals(""))
 handleReceive(context, intent);

private void handleReceive(Context context, Intent intent)
 //This can change depending on what you get from your server
 //This shows how you can get a string from the Intent and create
 //a notification(not included)
 String payload = intent.getStringExtra("message");
 Log.d("C2DM", "Received Message: " + payload);
 createNotification(context, payload);

private void handleRegistration(Context context, Intent intent)
 String registration = intent.getStringExtra("registration_id");

 if(intent.getStringExtra("error") != null)
 //You shouldn't get an error, but this will tell you what it is.
 Log.e(C2DMReceiver.class.getName(), intent.getStringExtra("error"));
 else if(intent.getStringExtra("unregistered") != null)
 //Unless you want to unregister the device, this shouldn't happen.
 Log.e(C2DMReceiver.class.getName(), "Unregister sent to device!");
 else if(registration != null)
 //Store the registration key. You have to send this to your server.
 SharedPreferences prefs = CCDirector.theApp.getPreferences(Activity.MODE_PRIVATE);

 prefs.edit().putString("registrationid", registration)
 //Something happened, log the account and message
 String accountName = intent.getExtras().getString("account");
 String message = intent.getExtras().getString("message");

 if(message != null && accountName != null)
 Log.d(C2DMReceiver.class.getName(), accountName + ": " + message);

} //end class

If everything has gone correctly, you should now be C2DM ready!

Comments are closed.