如何使用C#向所有设备发送带有图像的FCM通知?

时间:2017-02-22 10:00:23

标签: c# android firebase push-notification firebase-cloud-messaging

有没有办法使用C#向所有设备广播FCM通知 - 加上图像

我想要包含图片并通过Firebase Notification服务发送到所有设备,而不是发送到一个特定的设备ID。

我使用此代码将数据发送到单个用户设备,但没有图像:

public string SendNotificationInstaTips(string firebaseID, 
        string notTitle
        string notText, 
        string notContent)
    {

        try
        {
            string SERVER_API_KEY = "AIza..QXq5OQCaM";
            string SENDER_ID = "162..09";                
            string REGISTERATION_ID = firebaseID;

            WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
            tRequest.Method = "post";
            tRequest.ContentType = "application/json";

            var data = new
            {
                to = REGISTERATION_ID,

                data = new
                {
                    title = notTitle,
                    text = notText
                    content = notContent
                }
            };
            var serializer = new JavaScriptSerializer();
            var json = serializer.Serialize(data);
            Byte[] byteArray = Encoding.UTF8.GetBytes(json);
            tRequest.Headers.Add(string.Format("Authorization: key={0}", SERVER_API_KEY));
            tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
            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();
                            return sResponseFromServer;
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

2 个答案:

答案 0 :(得分:0)

我一直在用PHP工作,但它应该在C#中类似。 在代码中使用“注册ID”代替“to”

var data = new
        {
            to = REGISTERATION_ID, //Change this line

            data = new
            {
                title = notTitle,
                text = notText
                content = notContent
            }
        };
var data = new
        {
            registration_ids = {"AIza..QXq5OQCaM","An2i..QXq5OQCaM", .....},

            data = new
            {
                title = notTitle,
                text = notText
                content = notContent
            }
        };

希望这会有所帮助

答案 1 :(得分:0)

这不是Push Notifications的常用用例。对于FCM,强烈建议不要发送图像,主要是因为有效载荷大小限制 - notification为2KB,data为4KB。

我建议使用Firebase Storage存储图片,然后在需要时将其下载到设备中,只需在推送通知中发送下载网址即可。

有关如何发送到多台设备的问题,请参阅我的answer here。我建议您的用例使用Topic Messaging