Monday, November 5, 2012

Android - GCM Sample

Hello


Following is a code sample for using GCM.
Client is android application.
Server is based on ASP.Net.

The sample is very naive and hard code is used:

  • The android app is invoked ,  GCMRegister performs registration if needed and regId is saved and used on the server as  strDeviceRegistrationId 
  • The ASP.Net is invoked, it use strDeviceRegistrationId  and GoogleApiKey , to send a message to this particular device
  • The android device "catch" this message via GCMBaseIntentService.onMessage


Client registration

GCMRegister

Important methods :
  • register
  • unregister
  • getRegistrationId

This code register for GCM and the device registration ID is retrived - regId

 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        try {
   GCMRegistrar.checkDevice(this);
   GCMRegistrar.checkManifest(this);
   final String regId = GCMRegistrar.getRegistrationId(this);
   if (regId.equals("")) {
     GCMRegistrar.register(this, Constants.SENDER_ID);
   } else {
     Log.v("TAG", "Already registered");
   }
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
        
    }     



GCMBaseIntentService

Important methods :

  • onError
  • onMessage
  • onRegistered
  • onUnregistered

Most important method is onMessage. the message is read via  intent.getStringExtra("message");

public class GCMIntentService extends GCMBaseIntentService{

 @Override
 protected void onError(Context arg0, String arg1) {
  
   //Called on registration or unregistration error.
  Log.v("TAG", "GCMIntentService onError");
 }

 @Override
 protected void onMessage(Context arg0, Intent intent) {
  // TODO Auto-generated method stub
  
  // ---   Called when a cloud message has been received.
  
  // --- handle here the push notification e.g. Toast Notification
  Log.v("TAG", "GCMIntentService onMessage");
  String message = intent.getStringExtra("message");
 }

 @Override
 protected void onRegistered(Context arg0, String arg1) {
  // TODO Auto-generated method stub
  
  // --- Called after a device has been registered. 
  
  Log.v("TAG", "GCMIntentService Registered");
 }

 @Override
 protected void onUnregistered(Context arg0, String arg1) {
  // TODO Auto-generated method stub
  
    // Called after a device has been unregistered.
  Log.v("TAG", "GCMIntentService UnRegistered");
 }

}



ASP.Net Server

The server uses :




PushNotification.cs
public class AndroidGCMPushNotification
{
    
    public string SendNotification(string deviceId, string message)
    {
        var value = message;
        WebRequest tRequest;
        tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
        tRequest.Method = "post";

        // --- text
        tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
        string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="
            + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + deviceId + "";

        

        tRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleApiKey));
        
        Console.WriteLine(postData);
        Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        tRequest.ContentLength = byteArray.Length;

        Stream dataStream = tRequest.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();

        WebResponse tResponse = tRequest.GetResponse();

        dataStream = tResponse.GetResponseStream();

        StreamReader tReader = new StreamReader(dataStream);

        String sResponseFromServer = tReader.ReadToEnd();


        tReader.Close();
        dataStream.Close();
        tResponse.Close();
        return sResponseFromServer;
    }

    

    public string GoogleApiKey
    {
        get { return m_strGoogleAppID; }
        set { m_strGoogleAppID = value; }
    }
   

    public string SenderId
    {
        get { return m_strSenderId; }
        set { m_strSenderId = value; }
    }


    string m_strSenderId;
    string m_strGoogleAppID;
}



first.aspx
<%@ Page Language="C#" %>






Sources :


Nathan

2 comments:

  1. Thanks for the post

    I've Some Question in "SendNotification" Method
    it has two parameters one for the `message` and the other `Device ID` for what ??

    From where I can get the Device_ID

    Thanks In Advance

    ReplyDelete