The following is my implememtation for using cloud to device messaging
1) I registered on the google site for using c2dm and i received a mail from them also.
So i guess my mail id to be used is correct
2) In my launcher activity i have the following code :-
Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new
Intent(), 0)); // boilerplate
registrationIntent.putExtra("sender", "mail-id");
startService(registrationIntent);
3) The following is my broadcast receiver code :-
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.d("in on recieve", "++++++++++++");
String a = intent.getAction();
if(a.equals("com.google.android.c2dm.intent.REGISTRATION")){
String regId = intent.getStringExtra("registration_id");
String error = intent.getStringExtra("error");
String unregistered = intent.getStringExtra("unregistered");
if(error!=null){
}else if(regId!=null){
//Toast.makeText(context, regId, Toast.LENGTH_LONG).show();
Intent i = new Intent(context, RegService.class);
i.putExtra("reg", regId);
context.startService(i);
}
}else if(a.equals("com.google.android.c2dm.intent.RECEIVE")){
String anothr = intent.getAction();
Toast.makeText(context, anothr, Toast.LENGTH_LONG).show();
Log.e("C2DM", "Message: Fantastic!!!");
// Extract the payload from the message
Bundle extras = intent.getExtras();
if (extras != null) {
System.out.println(extras.get("payload"));
Toast.makeText(context, (CharSequence) extras.get("payload"), Toast.LENGTH_LONG).show();
// Now do something smart based on the information
}
}
}
I am able to get the registration Id with this. and then the intent goes to my regService class explained in next point.
4) The following code is in my RegService class. It is also mentioned in the manifest file.
DataManager dataManager = DataManager.getInstance();
String regId;
String appId;
String s;
public RegService(){
super("Let it be");
//Toast.makeText(getApplicationContext(), "I got the power", Toast.LENGTH_LONG).show();
// TODO Auto-generated constructor stub
}
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method tub
Log.d("In IntentService","++++++++++++++");
regId = intent.getStringExtra("reg");
appId = dataManager.getAppUserId();
TelephonyManager telephonyManager = (TelephonyManager)this.getSystemService(TELEPHONY_SERVICE);
String devId = telephonyManager.getDeviceId();
Log.d("Reg Service", "regID -> "+regId+" devId -> "+devId);
authentification();
}
public void authentification(){
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(
"https://www.google.com/accounts/ClientLogin");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("Email", "MAIL-ID"));
nameValuePairs.add(new BasicNameValuePair("Passwd", "piku13nayahai"));
nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
nameValuePairs.add(new BasicNameValuePair("source",
"Google-cURL-Example"));
nameValuePairs.add(new BasicNameValuePair("service", "ac2dm"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
Log.e("HttpResponse", line);
if (line.startsWith("Auth=")) {
s = line.substring(5);
Log.d("Authentication Token",s);
//Toast.makeText(this, s, Toast.LENGTH_LONG).show();
}
}
} catch (IOException e) {
e.printStackTrace();
}
sendMessage();
}
public void sendMessage(){
try{
StringBuilder postDataBuilder = new StringBuilder();
postDataBuilder.append("registration_id").append("=")
.append(regId);
postDataBuilder.append("&").append("collapse_key").append("=")
.append("0");
postDataBuilder.append("&").append("data.payload").append("=")
.append(URLEncoder.encode("Some Message", "UTF-8"));
byte[] postData = postDataBuilder.toString().getBytes("UTF-8");
URL url = new URL("https://android.clients.google.com/c2dm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("Content-Length",
Integer.toString(postData.length));
conn.setRequestProperty("Authorization", "GoogleLogin auth="
+ s);
OutputStream out = conn.getOutputStream();
out.write(postData);
out.close();
int responseCode = conn.getResponseCode();
String responseLine = new BufferedReader(new InputStreamReader(
conn.getInputStream())).readLine();
Log.d("Response Code from send API",responseLine+"response code ->"+responseCode);
// NOTE: You *MUST* use exponential backoff if you receive a 503
// response code.
// Since App Engine's task queue mechanism automatically does this
// for tasks that
// return non-success error codes, this is not explicitly
// implemented here.
// If we weren't using App Engine, we'd need to manually implement
// this.
if (responseLine == null || responseLine.equals("")) {
Log.i("C2DM", "Got " + responseCode
+ " response from Google AC2DM endpoint.");
throw new IOException(
"Got empty response from Google AC2DM endpoint.");
}
String[] responseParts = responseLine.split("=", 2);
if (responseParts.length != 2) {
Log.e("C2DM", "Invalid message from google: " + responseCode
+ " " + responseLine);
throw new IOException("Invalid response from Google "
+ responseCode + " " + responseLine);
}
if (responseParts[0].equals("id")) {
Log.i("Tag", "Successfully sent data message to device: "
+ responseLine);
}
if (responseParts[0].equals("Error")) {
String err = responseParts[1];
Log.w("C2DM",
"Got error response from Google datamessaging endpoint: "
+ err);
// No retry.
throw new IOException(err);
}
}catch (Exception e) {
// TODO: handle exception
Log.d("In RegService Catch Block","++++++++++++++++++++++++++++++");
e.printStackTrace();
}
}
Now the issue is i am able to send the message which i can get to know from the log Cat itself. I get response code of 200 itself and i am able to send the message but can not receive it
Make sure you are not sending from the same email address as you are receiving from. It’s apparently known issues surrounding that.