Best Android push notification (C2DM) tutorials

14 07 2012

Here are the best tutorials (in my opinion) that I have found on the Internet about C2DM service for sending push notifications to Android device. There are three groups of them, each corresponds to one actor in the architecture. Details about Push notifications you can find in my previous post here.

1. Android application part tutorials

2. Server Part tutorials

3. C2DM Server instructions

  • Google developers site has all the information necessary to use C2DM Service (including registration, authentication and webservice requests and message formats)

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!

Advertisements




Android push notification tutorial: C2DM 3rd party Application server implementation

26 05 2012

Here is how to implement C2DM server part in java for Google C2DM service using apache http-client and http-impl apache libs for REST webservice calls:

Server Authentication in C2DM Service

In order to send message to C2DM Server, first you have to authenticate your server with valid google account. Here is how to do it.

Params:

private static final String PARAM_VALUE_SERVICE = "ac2dm";
private static final String PARAM_AUTH_SERVICE = "service";
private static final String PARAM_VALUE_ACCOUNT_TYPE = "GOOGLE";
private static final String PARAM_AUTH_ACCOUNT_TYPE = "accountType";
private static final String PARAM_AUTH_PASSWD = "Passwd";
private static final String PARAM_AUTH_EMAIL = "Email";
private static final String PARAM_AUTH_SOURCE = "source";

Authentication method (try-catch omitted):

public static String getAuthToken(String email, String password){
	HttpClient httpClient = new DefaultHttpClient();
	HttpPost httppost = new HttpPost("https://www.google.com/accounts/ClientLogin");
	// Add your data
	List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
	nameValuePairs.add(new BasicNameValuePair(PARAM_AUTH_EMAIL, email));
	nameValuePairs.add(new BasicNameValuePair(PARAM_AUTH_PASSWD, password));
	nameValuePairs.add(new BasicNameValuePair(PARAM_AUTH_ACCOUNT_TYPE, PARAM_VALUE_ACCOUNT_TYPE));
	nameValuePairs.add(new BasicNameValuePair(PARAM_AUTH_SOURCE, "your-app-name"));
	nameValuePairs.add(new BasicNameValuePair(PARAM_AUTH_SERVICE, PARAM_VALUE_SERVICE));

	httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");

	// Execute HTTP Post Request
	HttpResponse response = httpClient.execute(httppost);

	// Read the response
	BufferedReader reader = new BufferedReader(
			new InputStreamReader((response.getEntity().getContent())));
	String line = null;
	String auth_key = null;
	while ((line = reader.readLine()) != null) {
		if (line.startsWith("Auth=")) {
			auth_key = line.substring(5);
		}
	}
}

Authentication method call:

String auth_token = AuthenticationUtil.getAuthToken(ConstantsC2dm.C2DM_SENDER_EMAIL, ConstantsC2dm.C2DM_SENDER_EMAIL_PASSWORD);

Sending message to C2DM Server

To send push notification to C2DM Server you just need to make Http Post REST request to given URL. Some parameters are necessary to add (specified here):

public static final String PARAM_REGISTRATION_ID = "registration_id";
public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle";
public static final String PARAM_COLLAPSE_KEY = "collapse_key";
private static final String DATA_PREFIX = "data.";

Here is the message sender method code. In my message I pass two parameters: questionId and validUntil. App reads questionId and performs further actions (download data from App server based on given questionId. Note that Google C2DM service does not take part in further downloads. It just triggers an app to perform some action):

public static int sendMessage(String auth_token, String registrationId,
		String questionId, String validUntil) throws ClientProtocolException, IOException{
	// Create a new HttpClient and Post Header
	HttpClient httpClient = new DefaultHttpClient();
	HttpPost httppost = new HttpPost("https://android.clients.google.com/c2dm/send");

	// Add your data
	List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
	nameValuePairs.add(new BasicNameValuePair(PARAM_REGISTRATION_ID, registrationId));
	nameValuePairs.add(new BasicNameValuePair(PARAM_COLLAPSE_KEY, "0"));
	nameValuePairs.add(new BasicNameValuePair(DATA_PREFIX + ConstantsC2dm.PARAM_QUESTION_ID, questionId));
	nameValuePairs.add(new BasicNameValuePair(DATA_PREFIX + ConstantsC2dm.PARAM_VALID_UNTIL, validUntil));

	httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	httppost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
	httppost.addHeader("Authorization", "GoogleLogin auth="+ auth_token);

	// Execute HTTP Post Request
	HttpResponse response = httpClient.execute(httppost);

	return response.getStatusLine().getStatusCode();
}

Hope that helps.

Summary

This code can be used as a servlet, standalone java application, in jsp page or in Bean. Message sender can be triggered by some event (like incoming email in GMail) or by hand (after clicking a button on a webpage).

If any more help is needed – do not hesitate to ask.

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!





Android push notifications with Google C2DM

19 05 2012

Push notification is message sent by server logic to specific android device. Message can be caught by specified application and handled in any way. For example some notification can be shown on the android status bar. Received message can also be handled by Application in the way which user will not even see. Application will just update its configuration, perform some action and close without showing anything on GUI.

Android users are familiar with it – GMail synchronization works this way. GMail server sends notification to the Android smartphone right after there is a new mail on the GMail Server. Developers can also make use from these notifications.

It is realized by permanently opened socket in the Android OS, listening for the messages sent from server. It is built-in component present in all Androids 2.2 and higher.

How to Do it?

The best description and instruction is on the google site. Key points are listed in this part. There are three components in the architecture:

1. Android Device

2. Google C2DM Server

3. Your application’s server with logic that decides when and to which device to send push message

How does it work?

1. Android device registers in C2DM Service, and receives its unique registration ID, sends this Id to App server where it is stored. Registration ID has to be periodically refreshed.

2. When application server logic decides to send push message it sends it to Google C2DM Server (using REST Webservice request) giving registration ID of target Android device

3. Google C2DM Server delivers message to Android device or queues it and retries if device is currently not available in network

4. C2DM message is converted by android OS to intent and Android application that is listening for message from app server receives it  by intentBroadcast and handles it.

What is required?

  • Need to have c2dm account (fast & free to create here). In basic contract you have 200 000 notifications per day for free(testing and low production apps). It can be extended.
  • User’s Google account set up on the android device and Google Play App installed
  • Additional Google account to create C2DM account and authorize while sending push from Application server
  • Android 2.2 or higher
  • Application permissions and listeners registrations defined in AndroidManifest.xml. Presented here.
 Features
  • you can pass parameters in push message (However remember that message size limit is 1024 bytes)
    • rather include parameters with instructions to download data, not the date itself due to message size limit
  • I don’t know if there is any QoS or guarantees regarding delay and reliability of this service. however due to my observations – mostly it works well. in most cases the message is delivered after few seconds after sending it.
Alternatives for using C2DM
Alternatives enables You to skip Google C2DM Server and service, and implement permanently listenting socket on the android device on You own. If you believe that it can be better than C2DM – you should read this article where alternative ways are described.

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!








%d bloggers like this: