如何通过GCM派C#.NET Android的推送通知 [英] How to send Android push notifications via GCM on C# .Net

查看:294
本文介绍了如何通过GCM派C#.NET Android的推送通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的所有Android GCM推送通知和本人已阅读栈职位,但无法获得直answer.I也看过的创建的Andr​​oid 推送通知,以获得更好的理解GCM如何工作的。我也用了SDK提供的GCM-演示服务器和GCM-演示客户端。但是,这里有我的怀疑和我所到目前为止已经试过:




  1. 关于我已经把该链接,里面有应用注册的手机获得注册码。这是所有手机的唯一密钥,它使用相同的应用程序?

  2. 这是否注册密钥在任何情况下到期? (例如应用程序在后台运行)

  3. 假设我有注册码,我曾尝试下面的代码片段通过GCM推通知我的应用程序。这是写在C#.NET。请让我知道是否我所提到的东西可以用下面的代码段来实现:

     私人字符串SendGCMNotification(字符串apiKey,串POSTDATA,串postDataContentType =应用/ JSON)
    {
    ServicePointManager.ServerCertificateValidationCallback + =新RemoteCertificateValidationCallback(ValidateServerCertificate);

    //邮件内容
    字节[]的字节数组= Encoding.UTF8.GetBytes(POSTDATA);

    //创建请求
    HttpWebRequest的要求=(HttpWebRequest的)WebRequest.Create(https://android.googleapis.com/gcm/send);
    Request.Method =POST;
    Request.KeepAlive = FALSE;
    Request.ContentType = postDataContentType;
    Request.Headers.Add(的String.Format(授权:键= {0},apiKey));
    Request.ContentLength = byteArray.Length;

    流数据流= Request.GetRequestStream();
    dataStream.Write(字节数组,0,byteArray.Length);
    dataStream.Close();

    //发送消息

    {
    WebResponse的响应= Request.GetResponse();
    HttpStatusCode ResponseCode =((HttpWebResponse)响应).StatusCode;
    如果(ResponseCode.Equals(HttpStatusCode.Unauthorized)|| ResponseCode.Equals(HttpStatusCode.Forbidden))
    {
    变种文字=未经授权 - 需要新的令牌; (!ResponseCode.Equals(HttpStatusCode.OK))
    }
    ,否则如果
    {
    变种文字=从Web服务响应不OK;
    }

    StreamReader的读者=新的StreamReader(Response.GetResponseStream());
    串responseLine = Reader.ReadToEnd();
    Reader.Close();

    返回responseLine;
    }
    赶上(例外五)
    {
    }
    返回错误;
    }


  4. 有没有第一次发送推送通知,没有手机的直接方式?在我们的自定义服务器正在注册



解决方案

请参阅代码:

 公共类AndroidGCMPushNotification 
{
公共AndroidGCMPushNotification()
{
//
// TODO:在此处添加构造函数逻辑
//
}
公共字符串sendNotification时(字符串的DeviceID,字符串消息)
{
字符串SERVER_API_KEY =服务器API密钥
VAR SENDER_ID =申请号;
VAR值=消息;
的WebRequest tRequest;
tRequest = WebRequest.Create(https://android.googleapis.com/gcm/send);
tRequest.Method =邮报;
tRequest.ContentType =应用/的X WWW的形式了urlencoded;字符集= UTF-8;
tRequest.Headers.Add(的String.Format(授权:键= {0},SERVER_API_KEY));

tRequest.Headers.Add(的String.Format(发件人:ID = {0},SENDER_ID));

串POSTDATA =collapse_key的= score_update&安培; time_to_live = 108&安培; delay_while_idle = 1&安培; data.message =+价值+&放大器; data.time =+ System.DateTime.Now.ToString() +与& registration_id =+ DEVICEID +;
Console.WriteLine(POSTDATA);
字节[]的字节数组= Encoding.UTF8.GetBytes(POSTDATA);
tRequest.ContentLength = byteArray.Length;

流数据流= tRequest.GetRequestStream();
dataStream.Write(字节数组,0,byteArray.Length);
dataStream.Close();

WebResponse的tResponse = tRequest.GetResponse();

数据流= tResponse.GetResponseStream();

StreamReader的踏浪号=新的StreamReader(数据流);

字符串sResponseFromServer = tReader.ReadToEnd();


tReader.Close();
dataStream.Close();
tResponse.Close();
返回sResponseFromServer;
}
}



全球化志愿服务青年链接:



HTTP://www.codeproject。 COM /提示/ 434338 / Android的GCM-推送通知


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 better understanding of how GCM works. I have also used the gcm-demo-server and gcm-demo-client provided by the SDK. However, here are my doubts and what I have tried so far:

  1. Regarding the link I have put, the phone which has the app registers to get the registration key. Is this a unique key for all phones which uses the same app?
  2. Does this registration key expires in any case? (E.g. App running on background)
  3. Assuming that I have the registration key, I have tried the following code snippet to push notification via GCM to my app. This is written on c# .net. Please let me know whether what I have mentioned above can be achieved using the following code snippet:

         private string SendGCMNotification(string apiKey, string postData, string postDataContentType = "application/json")
        {
            ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);
    
            // MESSAGE CONTENT
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
    
            // CREATE REQUEST
            HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
            Request.Method = "POST";
            Request.KeepAlive = false;
            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();
    
            // SEND MESSAGE
            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";
        }
    

  4. Is there a direct way of sending push notifications without the phone first being registered in our custom server?

解决方案

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() + "&registration_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

这篇关于如何通过GCM派C#.NET Android的推送通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆