How to send a firebase message to topic from Android

白昼怎懂夜的黑 提交于 2020-06-12 08:53:10

问题


I want to send a message to FCM topics from within my Android app. Sending the message through the Firebase console is working well, but once a user executes a particular action, I want a message to be sent to all other users who have subscribed to a particular topic.

In the documentation there is this code:

// The topic name can be optionally prefixed with "/topics/".
String topic = "highScores";

// See documentation on defining a message payload.
Message message = Message.builder()
.putData("score", "850")
.putData("time", "2:45")
.setTopic(topic)
.build();

// Send a message to the devices subscribed to the provided topic.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);

I can't figure out from which class Message is. It is obviously not RemoteMessage.


回答1:


There is no way to send messages directly from one Android device to another device with Firebase Cloud Message. You will always need a server (or otherwise trusted environment) to do that. See this docs section showing how messages are sent and my answer. here: How to send one to one message using Firebase Messaging.

The code sample you shared is using the Admin SDK for Java to send a message, which is meant to be run in a trusted environment. It can't be used in your Android app.




回答2:


You can do it by Volley and FCM API

here an example to send notification from user to "newOrder" Topic and have title and body

RequestQueue mRequestQue = Volley.newRequestQueue(this);

        JSONObject json = new JSONObject();
        try {
            json.put("to", "/topics/" + "newOrder");
            JSONObject notificationObj = new JSONObject();
            notificationObj.put("title", "new Order");
            notificationObj.put("body", "New order from : " + phoneNum.replace("+", " "));
            //replace notification with data when went send data
            json.put("notification", notificationObj);

            String URL = "https://fcm.googleapis.com/fcm/send";
            JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL,
                    json,
                    response -> Log.d("MUR", "onResponse: "),
                    error -> Log.d("MUR", "onError: " + error.networkResponse)
            ) {
                @Override
                public Map<String, String> getHeaders() {
                    Map<String, String> header = new HashMap<>();
                    header.put("content-type", "application/json");
                    header.put("authorization", "key=yourKey");
                    return header;
                }
            };


            mRequestQue.add(request);
        } catch (JSONException e) {
            e.printStackTrace();
        }

Replace yourKey with server key in your project in firebase


UPDATE : as @frank say in correct answer You will always need a server (or otherwise trusted environment) to hold yourKey and make it not public

so this answer is already work and can send notifications from android to topic or token

but if anyone take your key can send also to your apps notifications in any time so i suggest to use firebase functions or any service on your server just make sure your key in trusted environment and not reachable

also when get key there two type : 1 - Server key 2 - Legacy server key

like firebase say below also i suggested to use first because is more flexible to change or deleted

Firebase has upgraded our server keys to a new version. You may continue to use your Legacy server key, but it is recommended that you upgrade to the newest version



来源:https://stackoverflow.com/questions/55948318/how-to-send-a-firebase-message-to-topic-from-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!