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.
- Create a new project in Google Console where the user will get SenderId and Browser Api Key.
- This SenderId will be used by the Android Mobile Developer to generate RegisterId. This registerId is unique for every mobile.
- Now the user sends the Push Notification to the GCM server using the RegisterId and BrowserApi Key.
- 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.
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="PushNotification.aspx.cs" Inherits="PushNotification" %>
-
- <!DOCTYPE html>
-
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:TextBox runat="server" ID="txt_message" TextMode="MultiLine" Height="124px" Width="336px"></asp:TextBox>
-
- </div>
- <div>
- <asp:Button ID="btn_send" Text="Send" runat="Server" OnClick="btn_send_Click" />
- <br />
- <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
- </div>
- </form>
- </body>
- </html>
Here is the code on button click to send Notification.
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Security;
- using System.Security.Cryptography.X509Certificates;
- using System.Text;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
-
- public partial class PushNotification : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
-
- }
- protected void btn_send_Click(object sender, EventArgs e)
- {
- //RegisterId you got from Android Developer.
- string deviceId = "XXXXXXXXXXXXXbQw:APA91bEU_CsohZ12YUXXXXXXXXXXXXXjJwzhzQGL2NIEKlri_9cfMHbehh7n2y03KO0s9EsupKT_ezRaOo13JNNm10xjRqxnE9pjCymPvV-PXb29z7doQRAnOqEawAXXXXXXXXXXXX";
-
- string message = "Demo Notification";
- string tickerText = "Patient Registration";
- string contentTitle = txt_message.Text;
- string postData =
- "{ \"registration_ids\": [ \"" + deviceId + "\" ], " +
- "\"data\": {\"tickerText\":\"" + tickerText + "\", " +
- "\"contentTitle\":\"" + contentTitle + "\", " +
- "\"message\": \"" + message + "\"}}";
-
- string response = SendGCMNotification("BrowserAPIKey", postData);
-
-
- Label1.Text = response;
-
- }
-
- private string SendGCMNotification(string apiKey, string postData, string postDataContentType = "application/json")
- {
- ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);
-
-
-
- byte[] byteArray = Encoding.UTF8.GetBytes(postData);
-
-
-
- HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
- Request.Method = "POST";
-
-
- Request.ContentType = postDataContentType;
- Request.Headers.Add(string.Format("Authorization: key={0}", apiKey));
- Request.ContentLength = byteArray.Length;
-
- Stream dataStream = Request.GetRequestStream();
- dataStream.Write(byteArray, 0, byteArray.Length);
- dataStream.Close();
-
-
-
- try
- {
- WebResponse Response = Request.GetResponse();
-
- HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
- if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
- {
- var text = "Unauthorized - need new token";
- }
- else if (!ResponseCode.Equals(HttpStatusCode.OK))
- {
- var text = "Response from web service isn't OK";
- }
-
- StreamReader Reader = new StreamReader(Response.GetResponseStream());
- string responseLine = Reader.ReadToEnd();
- Reader.Close();
-
- return responseLine;
- }
- catch (Exception e)
- {
- }
- return "error";
- }
-
-
- public static bool ValidateServerCertificate(
- object sender,
- X509Certificate certificate,
- X509Chain chain,
- SslPolicyErrors sslPolicyErrors)
- {
- return true;
- }
-
-
-
-
- }
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,