使用FCM将通知推送到Android(c#)

时间:2016-12-02 13:31:17

标签: android c#-4.0 firebase-cloud-messaging

我想使用FCM向Android发送推送通知并在C#中实现。

我使用了以下代码,它在Response中给出了我的ID,看起来一切正常。

但是我没有在设备中收到任何通知,因为设备ID是正确的,如果我通过FCM控制台发送通知,则会收到通知。

任何建议都会有所帮助。

由于

 var value = "This is first message to Android";
            WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
            tRequest.Method = "post";
            tRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
            tRequest.Headers.Add(string.Format("Authorization: key={0}", "AAAAosN-NoU:APA91bHg6Iv8qj2giVvSRVVFze4L6Si0VTwctkNaRRqlI7qffKAMPHo4fd52SgZcB8Ring-mnPrkqjodTGrSru_bXKRQD9n4eVxhs8pTbkXac1gotCM77EixMUXTplXhceIm1o20BVXvkHO1HQZBti990ijebUW1fg"));
            tRequest.Headers.Add(string.Format("Sender: id={0}", "699064530565"));

            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=" + "APA91bFD6jRdsSzQ37_rB2x4C8wJzcDzgdjZuhf4hFgzCndeESCEnHrW3sRQcwetljExhlEUrpquhdTW2C24qjtb-PJuUUhpnev3Zn_DDH6aF7PStFRPYvWSQcfLFd14sueLmbhCvcqr" + "";

            Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            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();
                        }
                    }
                }
            }

1 个答案:

答案 0 :(得分:0)

请查看您的PostData。以下是如何格式化数据的示例。

 var PostData= new

            {
                data = {your custom data you want to send},
                to = deviceId,

                notification = new

                {

                    body = "Got notify",

                    title = Alert,

                },
                priority ="normal"
            };

            var serializer = new JavaScriptSerializer();

            var json = serializer.Serialize(PostData);

            Byte[] byteArray = Encoding.UTF8.GetBytes(json);

您可以通过调试代码来分享确切的错误。希望以上代码可以解决您的问题。