简体   繁体   中英

FCM (Firebase Cloud Messaging) Send to multiple devices

I execute this code to push notifications to mobile device using FCM library

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;
    }

now, how to send message to multi device, assume that string deviceId parameter replaced with List devicesIDs.

can you help

Update: For v1 , it seems that registration_ids is no longer supported. It is strongly suggested that topics be used instead. Only the parameters shown in the documentation are supported for v1.


Simply use the registration_ids parameter instead of to in your payload. Depending also on your use case, you may use either Topic Messaging or Device Group Messaging .

Topic Messaging

Firebase Cloud Messaging (FCM) topic messaging allows you to send a message to multiple devices that have opted in to a particular topic . Based on the publish/subscribe model, topic messaging supports unlimited subscriptions for each app. You compose topic messages as needed, and Firebase handles message routing and delivering the message reliably to the right devices.

For example, users of a local weather forecasting app could opt in to a "severe weather alerts" topic and receive notifications of storms threatening specified areas. Users of a sports app could subscribe to automatic updates in live game scores for their favorite teams. Developers can choose any topic name that matches the regular expression: "/topics/[a-zA-Z0-9-_.~%]+" .


Device Group Messaging

With device group messaging, app servers can send a single message to multiple instances of an app running on devices belonging to a group. Typically, "group" refers a set of different devices that belong to a single user . All devices in a group share a common notification key, which is the token that FCM uses to fan out messages to all devices in the group.

Device group messaging makes it possible for every app instance in a group to reflect the latest messaging state. In addition to sending messages downstream to a notification key, you can enable devices to send upstream messages to a device group. You can use device group messaging with either the XMPP or HTTP connection server. The limit on data payload is 2KB when sending to iOS devices, and 4KB for other platforms.

The maximum number of members allowed for a notification_key is 20.


For more details, you can check out the Sending to Multiple Devices in FCM docs.

You should create a Topic and let users subscribe to that topic. That way, when you send an FCM message, every user subscribed gets it, except you actually want to keep record of their Id's for special purposes.

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

See this link: 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!",
   }
}

Please follow these steps.

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");

}

I hope the above code will help you to send push on multiple devices. For more detail please refer this link https://firebase.google.com/docs/cloud-messaging/android/device-group

***Note : Please must read the about creating/removing group by the above link.

A word of caution mentioned in FCM DOcument which is as follows,

Caution: Any apps that use device group messaging must continue to use the legacy API for the management of device groups (creating, updating, etc.). The HTTP v1 can send messages to device groups, but does not support management.

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

Also the Admin SDK's uses a Batch HttpPostrequest to make it easy for consumers, so if you want Device Group messaging you could still uses the New V1 FCM API, but using FCM Admin SDK.

Here is the code from Admin SDK which does this job for you.

Class Name: 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); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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