FCM(Firebase云消息传递)发送到多个设备

时间:2016-09-17 13:18:03

标签: android asp.net firebase-cloud-messaging

我执行此代码以使用FCM库将通知推送到移动设备

public string PushFCMNotification(string deviceId, string message) 
    {
        string SERVER_API_KEY = "xxxxxxxxxxxxxxxxxxxxxxx";
        var SENDER_ID = "xxxxxxxxx";
        var value = message;
        WebRequest tRequest;
        tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
        tRequest.Method = "post";
        tRequest.ContentType = "application/json";
        tRequest.Headers.Add(string.Format("Authorization: key={0}", SERVER_API_KEY));

        tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));

        var data = new
        {
            to = deviceId,
            notification = new
            {
                body = "This is the message",
                title = "This is the title",
                icon = "myicon"
            }
        };

        var serializer = new JavaScriptSerializer();
        var json = serializer.Serialize(data);

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

        tRequest.ContentLength = byteArray.Length;

        Stream dataStream = tRequest.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();

        WebResponse tResponse = tRequest.GetResponse();

        dataStream = tResponse.GetResponseStream();

        StreamReader tReader = new StreamReader(dataStream);

        String sResponseFromServer = tReader.ReadToEnd();


        tReader.Close();
        dataStream.Close();
        tResponse.Close();
        return sResponseFromServer;
    }

现在,如何向多设备发送消息, 假设字符串deviceId参数替换为List devicesIDs。

你能帮忙吗

4 个答案:

答案 0 :(得分:26)

更新:对于 v1 ,似乎不再支持registration_ids。强烈建议使用主题。 v1仅支持documentation中显示的参数。

只需在有效负载中使用registration_ids参数代替to即可。根据您的使用情况,您可以使用Topic MessagingDevice Group Messaging

  

主题消息

     

Firebase云消息传递(FCM)主题消息传递允许您向已选择加入特定主题的多个设备发送消息。基于发布/订阅模型,主题消息传递支持每个应用程序的无限订阅。您可以根据需要撰写主题消息,Firebase可以处理消息路由并将消息可靠地传递给正确的设备。

     

例如,本地天气预报应用的用户可以选择加入恶劣天气警报"主题并接收威胁指定区域的风暴通知。体育应用的用户可以为他们喜欢的球队订阅实时比赛分数的自动更新。开发人员可以选择与正则表达式匹配的任何主题名称:"/topics/[a-zA-Z0-9-_.~%]+"

  

设备组消息

     

通过设备组消息传递,应用服务器可以将单个消息发送到在属于某个组的设备上运行的应用的多个实例。 通常," group"是指属于单个用户的一组不同设备。组中的所有设备共享一个公共通知密钥,该密钥是FCM用于将消息扇出到组中所有设备的标记。

     

设备组消息传递使组中的每个应用程序实例都能够反映最新的消息传递状态。除了向下游发送消息到通知密钥之外,您还可以启用设备以将上游消息发送到设备组。您可以将设备组消息传递与XMPP或HTTP连接服务器一起使用。发送到iOS设备时,数据有效负载的限制为2KB,其他平台的限制为4KB。

     

notification_key允许的最大成员数为20。

有关详细信息,请查看Sending to Multiple Devices in FCM文档。

答案 1 :(得分:8)

您应该创建一个主题并让用户订阅该主题。 这样,当您发送FCM消息时,每个订阅的用户都会获得它,除非您实际上想要为特殊目的记录其ID。

www.mydomain.biz

请参阅此链接:https://firebase.google.com/docs/cloud-messaging/android/topic-messaging

FirebaseMessaging.getInstance().subscribeToTopic("news");

答案 2 :(得分:5)

请按照以下步骤操作。

public String addNotificationKey(
    String senderId, String userEmail, String registrationId, String idToken)
    throws IOException, JSONException {
URL url = new URL("https://android.googleapis.com/gcm/googlenotification");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);

// HTTP request header
con.setRequestProperty("project_id", senderId);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");
con.connect();

// HTTP request
JSONObject data = new JSONObject();
data.put("operation", "add");
data.put("notification_key_name", userEmail);
data.put("registration_ids", new JSONArray(Arrays.asList(registrationId)));
data.put("id_token", idToken);

OutputStream os = con.getOutputStream();
os.write(data.toString().getBytes("UTF-8"));
os.close();

// Read the response into a string
InputStream is = con.getInputStream();
String responseString = new Scanner(is, "UTF-8").useDelimiter("\\A").next();
is.close();

// Parse the JSON string and return the notification key
JSONObject response = new JSONObject(responseString);
return response.getString("notification_key");

}

我希望上面的代码可以帮助您在多个设备上发送推送。 有关详细信息,请参阅此链接https://firebase.google.com/docs/cloud-messaging/android/device-group

***注意:请通过以上链接阅读有关创建/删除组的信息。

答案 3 :(得分:0)

FCM文档中提到的警告语如下,

警告:所有使用设备组消息传递的应用程序都必须继续使用旧版API来管理设备组(创建,更新等)。 HTTP v1可以将消息发送到设备组,但是不支持管理。

https://firebase.google.com/docs/cloud-messaging/migrate-v1

此外,管理SDK还使用批处理HttpPostrequest来简化使用程序,因此,如果您希望使用设备组消息传递,仍可以使用New V1 FCM API,但要使用FCM Admin SDK。

这是Admin SDK中的代码,可以为您完成这项工作。

类名称:FirebaseMessagingClientImpl

    for (Message message : messages) {
      // Using a separate request factory without authorization is faster for large batches.
      // A simple performance test showed a 400-500ms speed up for batches of 1000 messages.
      HttpRequest request = childRequestFactory.buildPostRequest(
          sendUrl,
          new JsonHttpContent(jsonFactory, message.wrapForTransport(dryRun)));
      request.setParser(jsonParser);
      setCommonFcmHeaders(request.getHeaders());
      batch.queue(
          request, MessagingServiceResponse.class, MessagingServiceErrorResponse.class, callback);
    }

相关问题