简体   繁体   English

用于GCM的服务器将通知推送到C#中的android

[英]Server for GCM push notification to android in C#

I am working on an android application which uses push notification service by GCM. 我正在开发一个使用GCM推送通知服务的Android应用程序。 Currently I am stuck at creating a server. 目前我被困在创建服务器。 The guides provided by the GCM documentation is in java which I have no idea how to implement. GCM文档提供的指南在java中,我不知道如何实现。 After researching for awhile, I found GCMSharp on github which uses C# 经过一段时间的研究,我在github上找到了使用C#的GCMSharp

PushSharp - https://github.com/Redth/PushSharp PushSharp - https://github.com/Redth/PushSharp

But as of now, I am new to creating a server and have no idea how to get started. 但截至目前,我是创建服务器的新手,并不知道如何开始。 Is the server actually a web service that keeps listening to request and upon getting a request directs it to the GCM which pushes notification to the client phone? 服务器实际上是一个持续监听请求的Web服务,并在收到请求后将其指向GCM,将GCM通知客户端电话吗?

And if yes, do I implement it in a webservice such as WCF? 如果是的话,我是否可以在WCF等Web服务中实现它?

You could follow this tutorial. 你可以按照这个教程。

Is the server actually a web service that keeps listening to request and upon getting a request directs it to the GCM which pushes notification to the client phone? 服务器实际上是一个持续监听请求的Web服务,并在收到请求后将其指向GCM,将GCM通知客户端电话吗?

You don't need to listen to requests. 您无需收听请求。 GCM Push directly pushes any message to the device without any request. GCM Push直接将任何消息推送到设备,无需任何请求。 For more details, Read this documentation . 有关更多详细信息,请阅读此文档

I have answered to this on another thread and here i am repeating. 我在另一个帖子上回答了这个问题,我在这里重复一遍。 Code looks bit longer but it works. 代码看起来有点长,但它有效。 I just sent a push notification to my phone after struggling 2 days by implementing the following code in C# project. 通过在C#项目中实现以下代码,我在困难的2天后向我的手机发送了推送通知。 I referred a link regarding this implementation, But couldn't find it to post here. 我提到了一个关于这个实现的链接,但是找不到它在这里发布。 So will share my code with you. 所以将与您分享我的代码。 If you want to test the Notification online you may visit to this link . 如果您想在线测试通知,可以访问此链接

note : I have hardcorded apiKey, deviceId and postData, please pass the apiKey,deviceId and postData in your request and remove them from the method body. 注意:我有硬编码的apiKey,deviceId和postData,请在你的请求中传递apiKey,deviceId和postData,并从方法体中删除它们。 If you want pass message string also 如果你想传递消息字符串也

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

You may not familiar with words like apiKey, deviceId. 您可能不熟悉apiKey,deviceId等词。 Dont worry i will explain what are they and how to create those. 别担心我会解释它们是什么以及如何创建它们。

apiKey apiKey
What & why :This a key that will be used when sending requests to GCM server. 内容和原因:这是在向GCM服务器发送请求时使用的密钥。
How to create : Refer this post 如何创建: 参考这篇文章

deviceId 设备编号
What & why : This id also known as RegistrationId. 什么和为什么:这个id也称为RegistrationId。 This is a unique id to identify the device. 这是识别设备的唯一ID。 When you want to send a notification to a specific device you need this id. 如果要向特定设备发送通知,则需要此ID。
How to create: This depends on how you implement the application. 如何创建:这取决于您实现应用程序的方式。 For cordova i used a simple pushNotification Plugin You can simply create a deviceId/RegistrationId using this plugin. 对于cordova,我使用了一个简单的pushNotification插件你可以使用这个插件简单地创建一个deviceId / RegistrationId。 To do that you need to have a senderId . 要做到这一点,你需要有一个senderId Google how to create a senderId it is really simple =) 谷歌如何创建senderId它真的很简单=)

If anyone needs some help leave a comment. 如果有人需要帮助,请发表评论。

Happy Coding. 快乐的编码。
-Charitha- -Charitha-

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM