Showing posts with label c2dm. Show all posts
Showing posts with label c2dm. Show all posts

Tuesday, May 17, 2011

Third Party Applcation Server

The Third Party Server is *your* server and can actually be any process written in any language (for example, it can be a batch process or a cron script). The role of the 3rd party "server" is to send the message to the device.

The Server will store (or update) the registrationID received into its local database. So, eventually the server will have registrationIDs from the devices.
Your server needs to get a ClientLogin Auth token in order to talk to the C2DM servers. When it wants to push a message to the device.
For ClientLogin Auth_Token: Click Here

To send a message to a particular device, the Server needs to POST to the C2DM Service the following 4 things:
  1.  The accountName which will be arxxus.pushapp@gmail.com .
  2. An authentication Token.
  3. The registrationID of the device it wants to send the message. 
  4. The message itself (Message limit 1024 Bytes)



Code:

// Create a new HttpClient and Post Header 
HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost("https://android.apis.google.com/c2dm/send"); 

//Your Authorization Token
httppost.addHeader("Authorization", "GoogleLogin auth="+authToken); 
httppost.addHeader("Content-Type","application/x-www-form-urlencoded"); 
            
// Add your data 
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
nameValuePairs.add(new BasicNameValuePair("registration_id",regId)); 
nameValuePairs.add(new BasicNameValuePair("collapse_key", "TEST")); 

//.<message> is the key and Message is "Push Contact"
nameValuePairs.add(new BasicNameValuePair("data.message","Push Contact")); 
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8")); 

// Execute HTTP Post Request 
System.out.println("Executing  sendMessage"); 
HttpResponse response = httpclient.execute(httppost); 
System.out.println(response.getStatusLine()); 
if (response.getEntity() != null) 
         System.out.println(EntityUtils.toString(response.getEntity())); 
}

This code work properly on Apache Tomcat Server but while deploying this code on the Google App Engine you will get the Restricted class issues..So if you are thinking of deploying on Google App Engine Try this...

// Send a sync message to this Android device.

URL url = new URL("https://android.apis.google.com/c2dm/send");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Authorization", "GoogleLogin auth="+Constants.authToken); 
urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Accept", "text/html, */*");
urlConnection.setRequestProperty("Connection", "keep-alive");

//Send MEssage
StringBuilder postDataBuilder = new StringBuilder();
postDataBuilder.append("registration_id"). append("=").append("YOUR_REGISTRATION_ID");
postDataBuilder.append("&").append("collapse_key").append("=").append("TEST");
postDataBuilder.append("&").append("data.message").append("=").append(message);
byte[] postData = postDataBuilder.toString().getBytes(URLEncoder.encode("UTF-8"));

//Executing  sendMessage
OutputStream outputStream = urlConnection.getOutputStream();
outputStream.write(postData);
outputStream.close();

int responseCode = urlConnection.getResponseCode();

If you like this post..Please do comments..



THANKS...









Wednesday, May 11, 2011

ClientLogin for Installed Applications for C2DM - Tutorial

Before you can write client applications that use the C2DM feature, you must have an HTTPS application server that meets the following criteria:Able to communicate with your client.
  • Able to fire off HTTP requests to the C2DM server.
  • Able to handle requests and queue data as needed. For example, it should be able to perform exponential back off.
  •  Able to store the ClientLogin Auth token and client registration IDs. The ClientLogin Auth token is included in the header of POST requests that send messages. For more discussion of this topic, see ClientLogin for Installed Applications. The server should store the token and have a policy to refresh it periodically.

The ClientLogin authorization process:
Authorization with ClientLogin involves a sequence of interactions between three entities: the installed application, Google services, and the user. This diagram illustrates the sequence:













  1. When the third-party application needs to access a user's Google service, it retrieves the user's login name and password.
  2. The third-party application then makes a ClientLogin call to Google's Authorization service.
  3. If the Google Authorization service decides additional vetting is necessary, it returns failure response with a CAPTCHA token and challenge, in the form of a URL for a CAPTCHA image. 
  4. If a CAPTCHA challenge is received, the third-party application displays the CAPTCHA image for the user and solicits an answer from the user. 
  5. If requested, the user submits an answer to the CAPTCHA challenge. 
  6. The third-party application makes a new ClientLogin call, this time including the CAPTCHA answer and token (received with the failure response). 
  7. On a successful login attempt (with or without CAPTCHA challenge), the Google Authorization service returns a token to the application. 
  8. The application contacts the Google service with a request for data access, referencing the token received from the Google Authorization service. 
  9. If the Google service recognizes the token, it supplies the requested data access.


How the Application Server Sends Messages

This section describes how the third-party application server sends messages to a 3rd party client application running on a mobile device.
Before the third-party application server can send a message to an application, it must have received a registration ID from it.
To send a message, the application server issues a POST request to https://android.apis.google.com/c2dm/send that includes the following:
FieldDescription
registration_idThe registration ID retrieved from the Android application on the phone. Required.
collapse_keyAn arbitrary string that is used to collapse a group of like messages when the device is offline, so that only the last message gets sent to the client. This is intended to avoid sending too many messages to the phone when it comes back online. Note that since there is no guarantee of the order in which messages get sent, the "last" message may not actually be the last message sent by the application server. Required.
data.<key>
Payload data, expressed as key-value pairs. If present, it will be included in the Intent as application data, with the <key>. There is no limit on the number of key/value pairs, though there is a limit on the total size of the message. Optional.
delay_while_idleIf included, indicates that the message should not be sent immediately if the device is idle. The server will wait for the device to become active, and then only the last message for each collapse_key value will be sent. Optional.
Authorization: GoogleLogin auth=[AUTH_TOKEN]Header with a ClientLogin Auth token. The cookie must be associated with the ac2dm service. Required.


This table lists the possible response codes:
ResponseDescription
200
Includes body containing:
  • id=[ID of sent message]
  • Error=[error code]
    • QuotaExceeded — Too many messages sent by the sender. Retry after a while.
    • DeviceQuotaExceeded — Too many messages sent by the sender to a specific device. Retry after a while.
    • InvalidRegistration — Missing or bad registration_id. Sender should stop sending messages to this device.
    • NotRegistered — The registration_id is no longer valid, for example user has uninstalled the application or turned off notifications. Sender should stop sending messages to this device.
    • MessageTooBig — The payload of the message is too big, see the limitations. Reduce the size of the message.
    • MissingCollapseKey — Collapse key is required. Include collapse key in the request.
503Indicates that the server is temporarily unavailable (i.e., because of timeouts, etc ). Sender must retry later, honoring any Retry-After header included in the response. Application servers must implement exponential back off. Senders that create problems risk being blacklisted.
401Indicates that the ClientLogin AUTH_TOKEN used to validate the sender is invalid


Code:


// Create a new HttpClient and Post Header 
HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost("https://www.google.com/accounts/ClientLogin"); 
// this is for proxy settings 

HttpParams params = httpclient.getParams(); 
params.setParameter("content-type", "application/x-www-form-urlencoded"); 
try { 
           // Add your data 
           List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
           nameValuePairs.add(new BasicNameValuePair("accountType","HOSTED_OR_GOOGLE")); 
           nameValuePairs.add(new BasicNameValuePair("Email","ar*****.pushapp@gmail.com")); 
           nameValuePairs.add(new BasicNameValuePair("Passwd","W******21")); 
           nameValuePairs.add(new BasicNameValuePair("service", "ac2dm")); 
           nameValuePairs.add(new BasicNameValuePair("source",   "arxxus.push.1.1")); 
           httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
    
           // Execute HTTP Post Requestu 
           HttpResponse response = httpclient.execute(httppost); 
          System.out.println(response.getEntity().toString()); 
          BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
          StringBuffer sb = new StringBuffer(""); 
          String line = ""; 
          while ((line = in.readLine()) != null) 
          { 
                    sb.append(line); 
          } 
          in.close(); 
         String result = sb.toString(); 
         String authToken=result.substring(result.indexOf("Auth=")+5); 
         System.out.println("Token="+authToken); 
         System.out.println("REGID"+RegistrationId);
         System.out.println(authToken.trim());

}//try

This code work properly on Apache Tomcat Server but while deploying this code on the Google App Engine you will get the Restricted class issues..So if you are thinking of deploying on Google App Engine Try this...


HttpURLConnection urlConnection;
URL url = new URL("https://www.google.com/accounts/ClientLogin");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
 
StringBuilder content = new StringBuilder();
content.append("Email=").append("ar*******pp@gmail.com");
content.append("&Passwd=").append("W******");
content.append("&service=").append("ac2dm");
content.append("&source=").append( "arxxus.push.1.1");
content.append("&accountType").append("HOSTED_OR_GOOGLE");
   
OutputStream outputStream = urlConnection.getOutputStream();
outputStream.write(content.toString().getBytes("UTF-8"));
outputStream.close();
int responseCode = urlConnection.getResponseCode();
System.out.println(responseCode+"\tSuccess");
StringBuffer resp = new StringBuffer(); 
if (responseCode == HttpURLConnection.HTTP_OK) 
{
   InputStream inputStream = urlConnection.getInputStream();
     BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
     String line; 
     while ((line = rd.readLine()) != null) 
    
     if(line.startsWith("Auth="))
     {
     resp.append(line.substring(5)); 
     }
    
     rd.close(); 
}
String authToken=resp.toString();
System.out.println("AuthTOken"+authToken);


If you like this post..Please do comments..

Tuesday, May 10, 2011

Android Cloud to Device Messaging(C2DM) Tutorial

This tutorial is for getting started with Android Cloud to Device Messaging (C2DM) on Android. In the iOS world it is knows as “push notifications”.

This feature will definitely help developers and their apps to streamline and optimize the data transfers. This would mean that apps now do not have to poll their servers at regular intervals to check for updates. The servers will be able to send updates (like Push Notifications) to the devices and makes it easier for mobile applications to sync data with servers.


There are many different ways of accomplishing the same thing(polling,constant server connections,SMS messages).

C2DM Alternatives:

Polling: The application itself would periodically poll your servers to check for new messages. You would need to implement everything from queuing messages to writing the polling code. Alerts are no good if they’re delayed due to a low polling period but the more frequently you poll, the more the battery is going to die.

SMS: Android can intercept SMS messages and you could include a payload to tell the application what to do. But then why not just use SMS in the first place? SMS is costly.

Persistent Connection: This would solve the problem of periodic polling but would destroy the battery life.

Cloud to device messaging 


“Android Cloud to Device Messaging (C2DM) is a service that helps developers send data from servers to their applications on Android devices. The service provides a simple, lightweight mechanism that servers can use to tell mobile applications to contact the server directly, to fetch updated application or user data. The C2DM service handles all aspects of queueing of messages and delivery to the target application running on the target device.”

It is a server push service provided by Google so that 3rd party applications can push messages to their applications on android devices.
Here are a few basic things to know about C2DM:
  1. It requires Android 2.2; C2DM uses Google services which are present on any device running the Android Market. 
  2. It uses existing connections for Google services. This requires the users to sign into their Google account on Android. 
  3. It allows 3rd party servers to send lightweight data messages to their apps. The C2DM service is not designed for pushing a lot of user content; rather it should be used like a “tickle”, to tell the app that there is new data on the server, so the app can fetch it. 
  4. An application doesn’t need to be running to receive data messages. The system will wake up the app via an Intent broadcast when the the data message arrives, so long as the app is set up with the proper Intent Receiver and permissions. 
  5. No user interface is required for receiving the data messages. The app can post a notification (or display other UI) if it desires.
Here is how it works:

To enable C2DM, an application on the device registers with Google and get a registration ID, and sends the ID to its server.

An Android application needs to register with C2DM servers before receiving any message. To register it needs to send an Intent (com.google.android.c2dm.intent.REGISTER), with 2 extra parameters:
  • sender is the ID of the account authorized to send messages to the application, typically the email address of an account set up by the application's developer.
  • app is the application's ID, set with a PendingIntent to allow the registration service to extract application information.
For example:
Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0)); // boilerplate
registrationIntent.putExtra("sender", emailOfSender);
startService(registrationIntent);

The C2DM servers route the message to the device, and an Intent broadcast is sent to the app.

// Registration ID received via an Intent
public void onReceive(Context context, Intent intent) {
  String action = intent.getAction();
  if (“com.google.android.c2dm.intent.REGISTRATION”.equals(action)) {
    handleRegistration(context, intent);
  }
}
public void handleRegistration(Context context, Intent intent) {
  String id = intent.getExtra(“registration_id”);
  if ((intent.getExtra(“error”) != null) {
    // Registration failed.  Try again later, with backoff.
  } else if (id != null) {
    // Send the registration ID to the app’s server.
    // Be sure to do this in a separate thread.
  }
}
The app can unregister with C2DM when the user no longer wants messages to be pushed to it.
Intent unregIntent = new Intent("com.google.android.c2dm.intent.UNREGISTER");
unregIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0));
startService(unregIntent);

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...