Asp.net blogs

Monday, 12 May 2014

Push Notification On Android Using C#

Working Example to push notification on Android using C# 

using JdSoft.Apple.Apns.Notifications;
using Newtonsoft.Json.Linq;

 string regId =   "APA91bEFbLOkP56DfLtUeXD1xiap54BDxQa1iP321W_-                                                                                                          QnRSYEenap8uz8lk8hkieEHRMH4rr6cAN-XE14IO2rx4IEZiN0xQ4Yf39aTw63zHM6swbp8zfwB_MEF6fTPTKEwxhtcpUfdc1Xhik6u6gQZIz6pULifQ";

        var applicationID = "AIzaSyDK7e2fDNymJCl8toInDPmPTlUsSKE1wz0";
        var SENDER_ID = "572165304164";
        var value = "TextMessage";
        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));

        Dictionary<string, object> rows = new Dictionary<string, object>();
        JavaScriptSerializer objSerializable = new JavaScriptSerializer();
        List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
        Dictionary<string, object> row = new Dictionary<string, object>();


        rows.Add("Result", "Success");
        rows.Add("SenderName", SenderName);
        rows.Add("SenderID", SenderID);
        rows.Add("ReceiverID", ReceiverID);
        rows.Add("TextMessage", TextMessage);



        //Context.Response.Write(objSerializable.Serialize(rows));

        String postDatas = objSerializable.Serialize(rows);



        //Data_Post Format
        //string postDatas = "{'data': {'SenderName':'" + SenderName + "','SenderID': '" + SenderID + "','ReceiverID':'" + ReceiverID + "','TextMessage':'" + TextMessage + "'}}";
        //string postDatas = "{" + "data:" + "{" + "SenderName:" + SenderName + "','SenderID': '" + SenderID + "','ReceiverID':'" + ReceiverID + "','TextMessage':'" + TextMessage + "'}}";


        string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="
          + postDatas + "&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();