This sample application demonstrates an approach for Android “Cloud To Device Messaging” (C2DM).
First you need to signup your application at code.google.com/android/c2dm/signup.html. Store an account (“Role account email”) somewhere in your application. You will be use it each time you register to C2DM.
private static final String ACCOUNT = "[email protected]";
Application needs the registration ID that allows it to receive messages for a particular device. You may get the registration ID with C2DMessaging class. Use C2DMessaging.register(Context context, String account) method passing the current context and the application account as parameters.
... C2DMessaging.register(this, ACCOUNT); ...
After registration succeeds the registration ID will be stored. Use C2DMessaging.getRegistrationId(Context context) method to get the registration ID.
... C2DMessaging.getRegistrationId(this); ...
An application can unregister C2DM if it no longer wants to receive messages. Use the appropriate C2DMessaging.unregister(Context context) method passing the current context as parameter.
You may handle the registration and messaging by redefining the C2DMReceiver class methods.
-
public void onRegistrered(Context context, String registrationId) - on application registered
-
public void onUnregistered(Context context) - on application unregistered
-
public void onError(Context context, String errorId) - on error occured during the registration process
-
protected void onMessage(Context context, Intent intent) - on message incoming
The registration ID lasts until the application explicitly unregisters itself, or until Google refreshes the registration ID for your application. The third-party application server stores the registration ID and uses it to identify the particular device. So it is very important to send the recent registration ID to application server if you want to receive C2DM messages.
To see an example please launch the C2DM_Skeleton application in Android device emulator.