如何使用 Firebase 消息传递一对一消息 [英] How to send one to one message using Firebase Messaging

查看:17
本文介绍了如何使用 Firebase 消息传递一对一消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试阅读有关如何将消息从一台设备发送到另一台设备的官方文档和指南.我已经在实时数据库中保存了两个设备的注册令牌,因此我有另一个设备的注册令牌.我尝试了以下方式发送消息

I have been trying to read the official docs and guides about how to send message from one device to another. I have saved registration token of both devices in the Real Time Database, thus I have the registration token of another device. I have tried the following way to send the message

RemoteMessage message = new RemoteMessage.Builder(getRegistrationToken())
                    .setMessageId(incrementIdAndGet())
                    .addData("message", "Hello")
                    .build();
FirebaseMessaging.getInstance().send(message);

但是这不起作用.另一台设备没有收到任何消息.我什至不确定是否可以使用上游消息发送来进行设备到设备的通信.

However this is not working. The other device doesn't receive any message. I am not even sure, if I can use upstream message sending to conduct device to device communication.

PS:我只想知道是否可以使用 FCM 进行设备到设备的消息传递?如果是,那么我使用的代码是否有问题?如果是,那么正确的方法是什么.

PS: I just want to know if device-to-device messaging is possible using FCM? If yes, then is the code I used have some issue? If yes, then what is the correct way.

更新:
我的问题是询问设备到设备的消息传递是否可能在不使用除 firebase 之外的任何单独服务器的情况下进行消息传递,如果是,而不是如何,因为没有关于它的文档.我不明白这里还有什么要解释的?无论如何,我得到了答案,并会在问题重新打开后将其更新为答案.

Update:
My question was to ask whether device to device messaging without using any separate server other than firebase could messaging is possible or not, if yes than how, since there's no documentation about it. I do not understand what is left to explain here? Anyways I got the answer and will update it as an answer once the question gets reopened.

推荐答案

警告我们没有在任何地方提及这种方法有一个非常重要的原因.这会在 APK 中公开您的服务器密钥您放在每个客户端设备上.它可以(因此将)取自那里并可能导致您的项目被滥用.我强烈推荐反对采用这种方法,除了你只安装的应用程序您自己的设备.– 弗兰克·范·普菲伦

Warning There is a very important reason why we don't mention this approach anywhere. This exposes your server key in the APK that you put on every client device. It can (and thus will) be taken from there and may lead to abuse of your project. I highly recommend against taking this approach, except for apps that you only put on your own devices. – Frank van Puffelen

好的,所以 Frank 的回答是正确的,即 Firebase 本身并不支持设备到设备的消息传递.但是,其中有一个漏洞.Firebase 服务器无法识别您是从实际服务器发送请求还是从您的设备发送请求.

Ok, so the answer by Frank was correct that Firebase does not natively support device to device messaging. However there's one loophole in that. The Firebase server doesn't identify whether you have send the request from an actual server or are you doing it from your device.

因此,您所要做的就是将 Post Request 连同服务器密钥一起发送到 Firebase 的消息传递服务器.请记住,服务器密钥不应该在设备上,但如果您希望使用 Firebase 消息传递进行设备到设备的消息传递,则没有其他选择.

So all you have to do is send a Post Request to Firebase's messaging server along with the Server Key. Just keep this in mind that the server key is not supposed to be on the device, but there's no other option if you want device-to-device messaging using Firebase Messaging.

我使用 OkHTTP 而不是调用 Rest API 的默认方式.代码是这样的 -

I am using OkHTTP instead of default way of calling the Rest API. The code is something like this -

public static final String FCM_MESSAGE_URL = "https://fcm.googleapis.com/fcm/send";
OkHttpClient mClient = new OkHttpClient();
public void sendMessage(final JSONArray recipients, final String title, final String body, final String icon, final String message) {

        new AsyncTask<String, String, String>() {
            @Override
            protected String doInBackground(String... params) {
                try {
                    JSONObject root = new JSONObject();
                    JSONObject notification = new JSONObject();
                    notification.put("body", body);
                    notification.put("title", title);
                    notification.put("icon", icon);

                    JSONObject data = new JSONObject();
                    data.put("message", message);
                    root.put("notification", notification);
                    root.put("data", data);
                    root.put("registration_ids", recipients);

                    String result = postToFCM(root.toString());
                    Log.d(TAG, "Result: " + result);
                    return result;
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(String result) {
                try {
                    JSONObject resultJson = new JSONObject(result);
                    int success, failure;
                    success = resultJson.getInt("success");
                    failure = resultJson.getInt("failure");
                    Toast.makeText(getCurrentActivity(), "Message Success: " + success + "Message Failed: " + failure, Toast.LENGTH_LONG).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getCurrentActivity(), "Message Failed, Unknown error occurred.", Toast.LENGTH_LONG).show();
                }
            }
        }.execute();
    }

String postToFCM(String bodyString) throws IOException {
        RequestBody body = RequestBody.create(JSON, bodyString);
        Request request = new Request.Builder()
                .url(FCM_MESSAGE_URL)
                .post(body)
                .addHeader("Authorization", "key=" + SERVER_KEY)
                .build();
        Response response = mClient.newCall(request).execute();
        return response.body().string();
    }

我希望 Firebase 将来会提供更好的解决方案.但在那之前,我认为这是唯一的方法.另一种方式是发送主题消息或群组消息.但这不在问题的范围内.

I hope Firebase will come with a better solution in future. But till then, I think this is the only way. The other way would be to send topic message or group messaging. But that was not in the scope of the question.

更新:
JSONArray 是这样定义的 -

Update:
The JSONArray is defined like this -

JSONArray regArray = new JSONArray(regIds);

regIds 是一个注册 id 的字符串数组,你想发送这个消息.请记住,注册 ID 必须始终位于数组中,即使您希望将其发送给单个收件人.

regIds is a String array of registration ids, you want to send this message to. Keep in mind that the registration ids must always be in an array, even if you want it to send to a single recipient.

这篇关于如何使用 Firebase 消息传递一对一消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆