How to send Android push notifications via GCM on C# .Net

后端 未结 6 1110
礼貌的吻别
礼貌的吻别 2020-12-13 08:02

I\'m new to all Android GCM push notifications and I have read stack posts but couldn\'t get a straight answer.I have also read Create push notification in android to get a

6条回答
  •  北海茫月
    2020-12-13 08:18

    Refer Code:

    public class AndroidGCMPushNotification
    {
        public AndroidGCMPushNotification()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        public string SendNotification(string deviceId, string message)
        {
            string SERVER_API_KEY = "server api key";        
            var SENDER_ID = "application number";
            var value = message;
            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}", 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=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "®istration_id=" + deviceId + "";
            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();
    
    
            tReader.Close();
            dataStream.Close();
            tResponse.Close();
            return sResponseFromServer;
        }
    }
    

    Referance Link:

    http://www.codeproject.com/Tips/434338/Android-GCM-Push-Notification

提交回复
热议问题