Sending Push Notifications to android device through Google Cloud Messaging using C#


Hello folks,

Last time we had documented the steps for registering your device with Google Cloud Messaging Push Notification service. Go to my previous blog.

This blog talks about sending custom Push Notification to the device registered with GCM.

Let's get started!



Step 1

You will need to store the registration IDs of all your clients in your database. Refer my previous blog for generating the registration ID.

Once you have done  that, either you can call all the IDs or send a custom notification to any particular user by calling the respective registration ID.

Step 2

Once you have the ID(s), you can use the following C# code to send the notifications.

 string regId = "<Registration ID>";    
 var applicationID = "<Your application ID>";  
   
 var SENDER_ID = "<Your Sender ID>";  
 var value = "<Notification Text>";  
 WebRequest tRequest;  
 tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");  
 tRequest.Method = "post";  
 tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";  
 tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));  
   
 tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));  
   
 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=" + regId + "";  
   
   
 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();  
   
 Label3.Text = sResponseFromServer; //printing response from GCM server.  
 tReader.Close();  
 dataStream.Close();  
 tResponse.Close();  
You can run a for loop for sending Push Notifications to various registration IDs.

Step 3

Once that is done, you can see the notification on the android phone in which the application is installed.

That's about it for sending Push Notification to your android device through GCM.

Peace and cheers!


Popular posts from this blog

Building your first Phonegap android application with HTML and JavaScript