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!


Actions

Information

5 responses

10 07 2012
Hasan

Hi,
Thanks for information abouth C2DM. I have a problem for ‘ConstantsC2dm’. Did you use any library? Does the ‘ConstantsC2dm’ provide to connection with google account?

11 07 2012
Jacek Milewski

No – ConstantsC2dm used here are two Strings referenced in few places in my code, so I used data class to avoid hardcoding.

ConstantsC2DM.PARAM_QUESTION_ID evaluates to “questionId”, and the ConstantsC2dm.PARAM_VALID_UNTIL is “validUntil” – these are my parameters names:)

DATA_PREFIX suffix in these lines is requirement from google – if You want to add your own parameters to C2DM message, you must add this prefix in params name, so google treats it as your params.

if you don’t need to pass parameters in C2DM message, just delete those two lines:
nameValuePairs.add(new BasicNameValuePair(DATA_PREFIX + ConstantsC2dm.PARAM_QUESTION_ID, questionId));
nameValuePairs.add(new BasicNameValuePair(DATA_PREFIX + ConstantsC2dm.PARAM_VALID_UNTIL, validUntil));

message will be sent anyway.

10 04 2013
registre des creations

sympa mais ce soir” il faut “vous décider mon site registre des creations

18 05 2013
bed bug heat

Great beat ! I wish to apprentice while you amend your website,
how can i subscribe for a blog site? The account
aided me a applicable deal. I have been tiny bit acquainted of
this your broadcast offered bright clear idea

2 07 2013
here

You made some decent points there. I looked on the web for more info about the issue and found
most individuals will go along with your views on this website.

Give Your feedback:

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: