用 C# 向 android 发送 GCM 推送通知的服务器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19241106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:29:14  来源:igfitidea点击:

Server for GCM push notification to android in C#

c#androidwcfgoogle-cloud-messaging

提问by user2857001

I am working on an android application which uses push notification service by GCM. 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. After researching for awhile, I found GCMSharp on github which uses C#

我正在开发一个使用 GCM 推送通知服务的 android 应用程序。目前我被困在创建服务器上。GCM 文档提供的指南是用 java 编写的,我不知道如何实现。经过一段时间的研究,我在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?

但截至目前,我是创建服务器的新手,不知道如何开始。服务器实际上是一个不断侦听请求并在收到请求后将其定向到将通知推送到客户端电话的 GCM 的 Web 服务吗?

And if yes, do I implement it in a webservice such as WCF?

如果是,我是否在 WCF 等网络服务中实现它?

采纳答案by Seshu Vinay

You could follow thistutorial.

您可以按照教程进行操作。

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?

服务器实际上是一个不断侦听请求并在收到请求后将其定向到将通知推送到客户端电话的 GCM 的 Web 服务吗?

You don't need to listen to requests. GCM Push directly pushes any message to the device without any request. For more details, Read this documentation.

您不需要听取请求。GCM Push 直接将任何消息推送到设备,无需任何请求。有关更多详细信息,请阅读此文档

回答by Charitha Goonewardena

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. 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.

我已经在另一个线程上回答了这个问题,在这里我重复一遍。代码看起来有点长,但它有效。通过在 C# 项目中实现以下代码,我在挣扎了 2 天后刚刚向我的手机发送了推送通知。我参考了有关此实现的链接,但找不到在此处发布的链接。所以将与您分享我的代码。如果您想在线测试通知,您可以访问此链接

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. If you want pass message string also

注意:我已经硬编码了 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;
}

You may not familiar with words like apiKey, deviceId. Dont worry i will explain what are they and how to create those.

apiKey、deviceId之类的词你可能不太熟悉。别担心,我会解释它们是什么以及如何创建它们。

apiKey
What & why :This a key that will be used when sending requests to GCM server.
How to create : Refer this post

deviceId
What & why : This id also known as RegistrationId. This is a unique id to identify the device. When you want to send a notification to a specific device you need this id.
How to create: This depends on how you implement the application. For cordova i used a simple pushNotification PluginYou can simply create a deviceId/RegistrationId using this plugin. To do that you need to have a senderId. Google how to create a senderId it is really simple =)

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

deviceId
What & 为什么:这个 id 也称为 RegistrationId。这是用于标识设备的唯一 ID。当您想向特定设备发送通知时,您需要此 ID。
如何创建:这取决于您如何实现应用程序。对于cordova,我使用了一个简单的pushNotification Plugin您可以使用这个插件简单地创建一个deviceId/RegistrationId。为此,您需要有一个senderId。Google 如何创建 senderId 真的很简单 =)

If anyone needs some help leave a comment.

Happy Coding.
-Charitha-

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

快乐编码。
-Charitha-