Push Notification To Android Mobile Using GCM (Google Cloud Messaging)

Introduction

 
In this article I am going to discuss about GCM architecture and describe how to send Push Notifications to Android Mobile. In one of my previous articles I have clearly described how to send Push Notifications to Google Chrome browser. You can view the following link:
Before this lets check what a PUSH NOTIFICATION is,
 
Push notification, also called server push notification, is the delivery of information from a software application to a computing device  like Mobile(Android,Iphone,Windows,etc),Tablet,etc without a specific request from the client.
 
These Notifications looks as follow.
 
 
 
GCM (Google cloud Messaging) is a free service provided by Google to send messages to different clients like (Android, iPhone, Chrome, Blackberry, etc).
 
GCM delivers messages only when the client is online. If the client is not online the GCM stores its notification inside a Queue, later when the client comes online then the message is delivered.
 
For receiving Push Notification your Android Client must be above 2.2.
 
 
For sending push notifications to any client we need three steps.
  1. Create a new project in Google Console where the user will get SenderId and Browser Api Key.
     
  2. This SenderId will be used by the Android Mobile Developer to generate RegisterId. This registerId is unique for every mobile.
     
  3. Now the user sends the Push Notification to the GCM server using the RegisterId and BrowserApi Key.
     
  4. The GCM will send the Notification to the required Mobile.
 
Now, the first step is to create a project in Google Console. Open the console and create a new project and give a new name.
 
 
After creating project copy the Project Number which is the SenderId. I have attached the screenshot here.
 
 
Now search for Google Cloud Messaging.
 
 
Click the Google Cloud Messaging for Android, iOS and Chrome and enable it.
 
 
 
After clicking Enable click Credentials.
 
 
Open the BrowserKey and save it.
 
 
Now copy the API key from it.
 
 
The work is finished. Now, the Android developer uses the previously created SenderId or project number to generate RegisterId.
 
NOTE
 
It is the task ofthe Aandroid developer to give you the RegisterId of the mobile using senderId. Don't waste time in searching for generating RegisterId.
 
You will get the RegisterId which is mentioned in Step two. Now after getting RegisterId we have to use the Register id and API key to send push notificationsto the GCM.
 
Here for sending messages I have designed the following UI.
 
Here I have attached the HTML code for this.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="PushNotification.aspx.cs" Inherits="PushNotification" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8. </head>  
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.     <div>  
  12.         <asp:TextBox runat="server" ID="txt_message" TextMode="MultiLine" Height="124px" Width="336px"></asp:TextBox>  
  13.       
  14.     </div>  
  15.         <div>  
  16.             <asp:Button ID="btn_send" Text="Send" runat="Server" OnClick="btn_send_Click" />  
  17.             <br />  
  18.             <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>  
  19.         </div>  
  20.     </form>  
  21. </body>  
  22. </html>  
 Here is the code on button click to send Notification.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Net;  
  6. using System.Net.Security;  
  7. using System.Security.Cryptography.X509Certificates;  
  8. using System.Text;  
  9. using System.Web;  
  10. using System.Web.UI;  
  11. using System.Web.UI.WebControls;  
  12.   
  13. public partial class PushNotification : System.Web.UI.Page  
  14. {  
  15.     protected void Page_Load(object sender, EventArgs e)  
  16.     {  
  17.   
  18.     }  
  19.     protected void btn_send_Click(object sender, EventArgs e)  
  20.     {  
  21.       //RegisterId you got from Android Developer.
  22.         string deviceId = "XXXXXXXXXXXXXbQw:APA91bEU_CsohZ12YUXXXXXXXXXXXXXjJwzhzQGL2NIEKlri_9cfMHbehh7n2y03KO0s9EsupKT_ezRaOo13JNNm10xjRqxnE9pjCymPvV-PXb29z7doQRAnOqEawAXXXXXXXXXXXX";  
  23.   
  24.         string message = "Demo Notification";  
  25.         string tickerText = "Patient Registration";  
  26.         string contentTitle = txt_message.Text;  
  27.         string postData =  
  28.         "{ \"registration_ids\": [ \"" + deviceId + "\" ], " +  
  29.           "\"data\": {\"tickerText\":\"" + tickerText + "\", " +  
  30.                      "\"contentTitle\":\"" + contentTitle + "\", " +  
  31.                      "\"message\": \"" + message + "\"}}";  
  32.   
  33.         string response = SendGCMNotification("BrowserAPIKey", postData);  
  34.   
  35.   
  36.         Label1.Text = response;  
  37.  
  38.     }  
  39.   
  40.      private string SendGCMNotification(string apiKey, string postData, string postDataContentType = "application/json")  
  41.         {  
  42.             ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);  
  43.   
  44.             //  
  45.             //  MESSAGE CONTENT  
  46.             byte[] byteArray = Encoding.UTF8.GetBytes(postData);  
  47.   
  48.             //  
  49.             //  CREATE REQUEST  
  50.             HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");  
  51.             Request.Method = "POST";  
  52.           //  Request.KeepAlive = false;  
  53.             
  54.             Request.ContentType = postDataContentType;  
  55.             Request.Headers.Add(string.Format("Authorization: key={0}", apiKey));  
  56.             Request.ContentLength = byteArray.Length;  
  57.   
  58.             Stream dataStream = Request.GetRequestStream();  
  59.             dataStream.Write(byteArray, 0, byteArray.Length);  
  60.             dataStream.Close();  
  61.   
  62.             //  
  63.             //  SEND MESSAGE  
  64.             try  
  65.             {  
  66.                 WebResponse Response = Request.GetResponse();  
  67.   
  68.                 HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;  
  69.                 if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))  
  70.                 {  
  71.                     var text = "Unauthorized - need new token";  
  72.                 }  
  73.                 else if (!ResponseCode.Equals(HttpStatusCode.OK))  
  74.                 {  
  75.                     var text = "Response from web service isn't OK";  
  76.                 }  
  77.   
  78.                 StreamReader Reader = new StreamReader(Response.GetResponseStream());  
  79.                 string responseLine = Reader.ReadToEnd();  
  80.                 Reader.Close();  
  81.   
  82.                 return responseLine;  
  83.             }  
  84.             catch (Exception e)  
  85.             {  
  86.             }  
  87.             return "error";  
  88.         }  
  89.         public static bool ValidateServerCertificate(  
  90.                                                      object sender,  
  91.                                                      X509Certificate certificate,  
  92.                                                      X509Chain chain,  
  93.                                                      SslPolicyErrors sslPolicyErrors)  
  94.         {  
  95.             return true;  
  96.         }  
  97. }  
Thus after sending it will show the following output which means the message is successfully delivered to the GCM server.
 
 
Note after sending message to the  GCM server the GCM server will identify the mobile using the RegisterId and notify the message to that mobile.
 
To know all the parameters used in this process and other details please check the following:
Hope this code will help you to know about GCM and sending Push Notification Using GCM.
 
Read more articles on Android,


Similar Articles