Click here to Skip to main content
15,895,786 members
Articles / Web Development / ASP.NET
Tip/Trick

Single Notification of Multiple Messages using GCM, if Device Idle

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
21 May 2013CPOL 17.5K   3  
How to send Single Notification of multiple messages using GCM, if device is Idle in ASP.NET

Introduction

If your device is idle but still connected, then message on GCM will still be delivered if the delay_while_idle flag is true. Otherwise, GCM server will store it till device is awake.

In this situation, collapse_key works.

To send the single notification from GCM of multiple messages if your device is idle, you just need to set the same collapse key each time with the single registration id. If there is already a message on GCm of the same collapse key and registration id and waiting for the delivery, then GCM will discard the old one and the new message is placed.

It means the old message is collapsed by the new message. But if the collapse key is not set, then both new and old message will be stored on GCM and delivered when the device is awake.

Here in the example, we assumed that if Ntype value is "C" means each time we need to send the same Collapse_key value with a single registration id. Generally, it is used to manage Chat message notifications in Android through GCM.

C#
public string SendMessage(string[] RegistrationID,
		string Message, string AuthString, string Ntype)
        {
            //-- Create C2DM Web Request O
            HttpWebRequest Request = (HttpWebRequest)
            WebRequest.Create("https://android.googleapis.com/gcm/send");
            Request.Method = "POST";
            Request.KeepAlive = false;
            string RegArr = string.Empty;

            RegArr = string.Join("\",\"", RegistrationID);

            string postData;
            if (Ntype == "C")// Send Single Notification For all messages of a
            	// regid if Device is not active by setting Collapse_Key value
            	// same for a particular regid each time
            {
                 postData = "{ \"registration_ids\": [ \"" + RegArr + "\" ] ,
                 		\"data\": {\"message\": \"" + Message +
                 		"\", \"collapse_key\":\"" + Ntype + "\"}}";
            }
            else
            {
                 postData = "{ \"registration_ids\": [ \"" + RegArr + "\" ] ,
                 		\"data\": {\"message\": \"" + Message + "\",
                 		\"collapse_key\":\"" + Message + "\"}}";
            }

           byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            Request.ContentType = "application/json";

           Request.Headers.Add("Authorization", "key=AIzaSyAoOORkueTJt-iJEqKEVmR8t6GKpA6200s");

           ServicePointManager.ServerCertificateValidationCallback += delegate(
                       object
                       sender,
                       System.Security.Cryptography.X509Certificates.X509Certificate
                       pCertificate,
                       System.Security.Cryptography.X509Certificates.X509Chain pChain,
                       System.Net.Security.SslPolicyErrors pSSLPolicyErrors)
           {
               return true;
           };

            //-- Create Stream to Write Byte Array --//
            Stream dataStream = Request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            //-- Post a Message --//

            WebResponse Response = Request.GetResponse();
            HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
            if (ResponseCode.Equals(HttpStatusCode.Unauthorized) ||
            	ResponseCode.Equals(HttpStatusCode.Forbidden))
            {
                return "Unauthorized - need new token";
            }
            else if (!ResponseCode.Equals(HttpStatusCode.OK))
            {
                return "Response from web service isn't OK";
            }

            StreamReader Reader = new StreamReader(Response.GetResponseStream());
            string responseLine = Reader.ReadLine();
            Reader.Close();

            return responseLine;
        }

Your Response of GCM would be like that:
{"multicast_id":7552490057639398244,"success":1,"failure":0,"canonical_ids":0,"results":
[{"message_id":"0:1368789540064966%3eb4175df9fd7ecd"}]{
/*===============================================================================*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using AndroitEntites.Entities.Common.Enums;
using AndroitEntites.Entities.Common;
using AndroitApp.DAL;


namespace AndroitApp.Settings
{
    public class NotificationMessage
    {
        string
      senderId ="abcd3430@gmail.com",//
            password = "abc@123";//"heeru.adroit";//


        StatusCls<int> oStatus = new StatusCls<int>();
        public int SendMultipleNotification(string senderVID, string message, string Type)
        {
            StatusCls<int> oStatus = new StatusCls<int>();
            DBHelper.TraceRequest("Notification Message", "Start", Convert.ToString(senderVID));
            try
            {
                string
                status = string.Empty;
                //senderId = string.Empty,
                //password = string.Empty;
                string[] regIds=null;
                string[] RecVID=null;
                int icount=0;

                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = "spr_Visitor_Get_UserRegId";
                    cmd.Parameters.AddWithValue("@VID", Convert.ToString(senderVID));
                    DataTable dt = DBHelper.SqlExecuteReader(cmd);

                    if (dt != null && dt.Rows.Count > 0)
                    {
                      icount= Convert.ToInt32(dt.Rows.Count.ToString());
                      regIds= new string[icount];
                      RecVID= new string [icount];

                      for (int row = 0; row < icount; row++)
                        {
                            regIds[row]= Convert.ToString( dt.Rows[row]["regid"]);
                            RecVID[row]= Convert.ToString(dt.Rows[row]["VisitorId"]);

                        }
                     }
                   }

                if (icount > 0)
                {
                    PushNotification oPush = new PushNotification();
                    status = oPush.Android(regIds, senderId, password, message, "N");

                    if (status.Contains("\"failure\":0"))
                    {
                        oStatus.Status = (int)Status.success;
                    }
                    foreach (string RID in RecVID)
                    {
                        oStatus.Status = AddMsg(senderVID, RID, message, Type);
                    }
                }
                else
                {
                    oStatus.Status = (int)Status.success;
                }
            }
            catch (Exception ex)
            {
                oStatus.Status = (int)Status.error;
            }

            return oStatus.Status;
        }

        public string SendSingleNotification(string senderVID,
        string receiverVID,string regid, string message, string MType)
        {
            string
                    status = string.Empty;
            try
            {
                    //senderId = string.Empty,
                    //password = string.Empty;

                string[] regId = new string[1];

                regId[0] = regid;
                //senderId = "skp9540@gmail.com";
                //password = "kishan@123";

                PushNotification oPush = new PushNotification();
                status = oPush.Android(regId, senderId, password, message,"N");
                AddMsg(senderVID, receiverVID, message, MType);
            }
            catch (Exception ex)
            {
                status = ex.Message.ToString();
            }

            return status;
        }

        public string SendChatNotification(string senderVID,
        string receiverVID, string regid, string message, string MType)
        {
            string
                    status = string.Empty;
            try
            {
                //senderId = string.Empty,
                //password = string.Empty;

                string[] regId = new string[1];

                regId[0] = regid;
                //senderId = "skp9540@gmail.com";
                //password = "kishan@123";

                PushNotification oPush = new PushNotification();
                status = oPush.Android(regId, senderId, password, message, "C");
                AddMsg(senderVID, receiverVID, message, MType);
            }
            catch (Exception ex)
            {
                status = ex.Message.ToString();
            }

            return status;
        }

        public int AddMsg(string SID, string RID, string msg, string Type)
        {
            StatusCls<int> oStatus = new StatusCls<int>();

            try
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = "spr_GCM_Add_Messages";
                    cmd.Parameters.AddWithValue("@SenderVID", Convert.ToString(SID));
                    cmd.Parameters.AddWithValue("@ReceiverVID", Convert.ToString(RID));
                    cmd.Parameters.AddWithValue("@Msg", Convert.ToString(msg));
                    cmd.Parameters.AddWithValue("@Type", Convert.ToString(Type));
                    DBHelper.SqlExecuteScaler(cmd);
                }

                oStatus.Status = (int)Status.success;
            }
            catch
            {
                oStatus.Status = (int)Status.error;
            }

            return oStatus.Status;
        }

        public string UserRegId(string receiverVID)
        {
            string regId = string.Empty;

            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "spr_GCM_Get_UserRegInfo";
                cmd.Parameters.AddWithValue("@VID", Convert.ToString(receiverVID));

                regId = (string)AndroitApp.DAL.DBHelper.SqlExecuteScaler(cmd);

            }

            return regId;
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --