繁体   English   中英

FCM(Firebase Cloud Messaging)发送到多个设备

[英]FCM (Firebase Cloud Messaging) Send to multiple devices

我执行此代码以使用 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。

你能帮我吗

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


只需在您的负载中使用registration_ids参数而不是to 根据您的用例,您可以使用Topic MessagingDevice Group Messaging

主题消息

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

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


设备组消息

通过设备组消息传递,应用服务器可以向在属于一个组的设备上运行的应用程序的多个实例发送一条消息。 通常,“组”是指属于单个用户的一组不同设备 组中的所有设备共享一个公共通知密钥,这是 FCM 用于向组中的所有设备发送消息的令牌。

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

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


有关更多详细信息,您可以查看FCM文档中的发送到多个设备

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

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

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

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{
  "to": "/topics/news",
  "data": {
    "message": "This is a Firebase Cloud Messaging Topic Message!",
   }
}

请按照以下步骤操作。

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

***注意:请务必阅读以上链接中关于创建/删除组的内容。

FCM DOcument 中提到的警告如下,

注意:任何使用设备群组消息的应用必须继续使用旧 API 来管理设备群组(创建、更新等)。 HTTP v1 可以向设备组发送消息,但不支持管理。

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

此外,Admin SDK 使用 Batch 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); }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM