如何在C#.Net上通过GCM发送Android推送通知

Pav*_*nda 9 c# android google-cloud-messaging

我是所有Android GCM推送通知的新手,我已经阅读过堆栈帖子,但无法得到直接答案.我还阅读了android中的创建推送通知,以便更好地了解GCM的工作原理.我还使用了SDK提供的gcm-demo-server和gcm-demo-client.但是,这是我的怀疑以及到目前为止我所尝试的内容:

  1. 关于我放的链接,有app的手机注册获取注册码.这是使用相同应用的所有手机的唯一键吗?
  2. 此注册密钥在任何情况下都会到期吗?(例如App在后台运行)
  3. 假设我有注册密钥,我尝试使用以下代码片段将GCM通知推送到我的应用程序.这是用c#.net编写的.请告诉我使用以下代码段是否可以实现上面提到的内容:

         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";
        }
    
    Run Code Online (Sandbox Code Playgroud)
  4. 是否有直接的方式发送推送通知,而无需先在我们的自定义服务器中注册电话?

Fre*_*cer 19

参考代码:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Referance链接:

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

  • GoogleAppID =服务器api密钥&& deviceid =注册ID(184个字符)&& SENDER_ID = 12位应用ID(项目编号)(感谢代码项目页面上的评论. (2认同)

Cha*_*ena 7

代码看起来有点长但是有效.通过在C#项目中实现以下代码,我在困难的2天后向我的手机发送了推送通知.我提到了一个关于这个实现的链接,但是找不到它在这里发布.所以将与您分享我的代码.如果您想在线测试通知,可以访问此链接.

注意:我有硬编码的apiKey,deviceId和postData,请在你的请求中传递apiKey,deviceId和postData,并从方法体中删除它们.如果你想传递消息字符串也

public string SendGCMNotification(string apiKey, string deviceId, string postData)
{
    string postDataContentType = "application/json";
    apiKey = "AIzaSyC13...PhtPvBj1Blihv_J4"; // hardcorded
    deviceId = "da5azdfZ0hc:APA91bGM...t8uH"; // hardcorded

    string message = "Your text";
    string tickerText = "example test GCM";
    string contentTitle = "content title GCM";
    postData =
    "{ \"registration_ids\": [ \"" + deviceId + "\" ], " +
      "\"data\": {\"tickerText\":\"" + tickerText + "\", " +
                 "\"contentTitle\":\"" + contentTitle + "\", " +
                 "\"message\": \"" + message + "\"}}";


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

public static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
    return true;
}
Run Code Online (Sandbox Code Playgroud)

您可能不熟悉apiKey,deviceId等词.别担心我会解释它们是什么以及如何创建它们.

apiKey
什么和为什么:这是在向GCM服务器发送请求时使用的密钥.
如何创建:参考这篇文章

deviceId
什么和为什么:这个id也称为RegistrationId.这是识别设备的唯一ID.如果要向特定设备发送通知,则需要此ID.
如何创建:这取决于您实现应用程序的方式.对于cordova,我使用了一个简单的pushNotification插件 你可以使用这个插件简单地创建一个deviceId/RegistrationId.要做到这一点,你需要有一个senderId.谷歌如何创建senderId它真的很简单=)

如果有人需要帮助,请发表评论.

快乐的编码.
-Charitha-