在Android设备上使用FCM发送推送通知

时间:2016-12-12 07:34:04

标签: c# asp.net firebase firebase-cloud-messaging

我可以使用控制台在我的Android应用程序上发送推送通知。但是使用服务器端代码,我得到了成功的消息发送通知,但实际上通知无法在设备端接收。请告诉我我的代码有什么问题:

public static string SendPushNotification() {
        try {
            string applicationID = "AAAA4GkXVHA:....-qRw";

            string senderId = "963..28";

            string deviceId = "APA91bHLV...IC4s";

            WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
            tRequest.Method = "post";
            tRequest.ContentType = "application/json";
            var data = new {
                to = deviceId,
                notification = new {
                    body = "hema",
                    title = "hem",
                    //priority = "normal",
                    //sound = "Enabled"
                },
            };

            var serializer = new JavaScriptSerializer();
            var json = serializer.Serialize(data);
            Byte[] byteArray = Encoding.UTF8.GetBytes(json);
            tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
            tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
            tRequest.ContentLength = byteArray.Length;
            using (Stream dataStream = tRequest.GetRequestStream()) {
                dataStream.Write(byteArray, 0, byteArray.Length);
                using (WebResponse tResponse = tRequest.GetResponse()) {
                    using (Stream dataStreamResponse = tResponse.GetResponseStream()) {
                        using (StreamReader tReader = new StreamReader(dataStreamResponse)) {
                            String sResponseFromServer = tReader.ReadToEnd();
                            string str = sResponseFromServer;
                            return str;
                        }
                    }
                }
            }
        }
        catch (Exception ex) {
            string str = ex.Message;
            return str;
        }
    }

我收到回复的地方如下:  {" multicast_id":8288766196764532656,"成功":1,"失效":0," canonical_ids":0,"结果& #34;:[{" MESSAGE_ID":" 0:1481612825945796%6ad79a87f9fd7ecd"}]}

3 个答案:

答案 0 :(得分:0)

以正确的格式发送json:

{
  "to" : "APA91bHLV__P6Qer8U70j82blZt0VdDgc2zo_4DtAD4_MtE-......",
  "notification" : {
    "body" : "Success!",
    "title" : "Hema",
    "icon" : "myicon"
  }
}

要正确检查,您还可以使用邮递员: Postman testing FCM server to device(ios or android)

答案 1 :(得分:0)

即使我遇到了同样的问题。完成从客户端连接FCM的所有步骤。如果您从客户端实现GetMessage()方法,则只有您的设备才能从服务器端获取通知

答案 2 :(得分:0)

我为此编写了一个小型教程:https://www.kendar.org/?p=/tutorials/notifications,其中包含一个Android应用程序和一个.Net核心服务器。这里总结一下“主”服务器代码

    public NotificationResult Send(NotificationModel messageData)
    {
        var result = "-1";
        var webAddr = "https://fcm.googleapis.com/fcm/send";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, "key=PROJECTSETTINGS->Cloud Messagings->Server Key");
        httpWebRequest.Method = "POST";
        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string strNJson = JsonConvert.SerializeObject(new NotificationMessage
            {
                To = "/topics/ServiceNow",
                Data = new NotificationData
                {
                    Description = messageData.Description,
                    IncidentNo = messageData.IncidentNo,
                    ShortDesc = messageData.ShortDesc
                },
                Notification = new Notification
                {
                    Title = "ServiceNow: Incident No." + messageData.IncidentNo,
                    Text = "Notification"
                }
            });
            streamWriter.Write(strNJson);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            result = streamReader.ReadToEnd();
        }

        return new NotificationResult
        {
            Result = result
        };
    }

以及将消息包装到FCM的类(带有Json批注以纠正.Net和Json命名标准之间的不匹配)

    public class NotificationData
{
    public string ShortDesc { get; set; }
    public long IncidentNo { get; set; }
    public string Description { get; set; }
}
public class Notification
{
    public Notification()
    {
        Sound = "default";
    }
    [JsonProperty("title")]
    public string Title { get; set; }
    [JsonProperty("text")]
    public string Text { get; set; }
    [JsonProperty("sound")]
    public string Sound { get; set; }
}
public class NotificationMessage
{
    [JsonProperty("to")]
    public string To { get; set; }
    [JsonProperty("data")]
    public NotificationData Data { get; set; }
    [JsonProperty("notification")]
    public Notification Notification { get; set; }

}