Send message to GCM in C#.NET for single or multiple device delivery

In previous articles we learnt about how google cloud messaging works and how to register android device on GCM for getting registration id.

Note: This post only explains how you can send same message to single or multiple devices but there is know method provided by GCM to send different message to different devices in one request.

Now we will see how we can send request to GCM server for sending notification to mobile devices. In this example we will use .NET as our server platform and C# as programming language.

For making code usable for single as well as multiple registration ids we have used list and converted it to comma separated strings. This comma separated string can be passed in our request and GCM server will relay our message to corresponding devices.

Below is the sample code:

public class NotificationManager
    {
        private class NotificationMessage
        {
            public string Title;
            public string Message;
            public long ItemId;
        }

         public NotificationManager()
        {
            //
            // TODO: Add constructor logic here
            //
        }

         public string SendNotification(List<string> deviceRegIds, string message, string title, long id)
        {
string SERVER_API_KEY = ;
var SENDER_ID = ;
string regIds = string.Join("","", deviceRegIds);

NotificationMessage nm = new NotificationMessage();
nm.Title = title;
nm.Message = message;
nm.ItemId = id;

var value = new JavaScriptSerializer().Serialize(nm);

WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
tRequest.Headers.Add(string.Format("Authorization: key={0}", SERVER_API_KEY));

tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));

string postData = "{"collapse_key":"score_update","time_to_live":108,"delay_while_idle":true,"data": { "message" : " + value + ","time": " + """ + System.DateTime.Now.ToString() + ""},"registration_ids":["" + regIds + ""]}";

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;
}
    }

In above example we have creates class named NotificationMessage for message format. We will convert object of this class to json and sent it as message.

In SendNotification method of the class, just pass list of registration ids along with message title, body and message id which we will use to show message on mobile device.

To use this code you have to create account on google developer console and generate credentials. Follow this article if you want to learn how to create account and generate credentials for GCM.

Leave a Reply