如何使用 Firebase 中的用户令牌向特定用户发送通知? [英] How can I send notification to specific User using the user's token in Firebase?

查看:55
本文介绍了如何使用 Firebase 中的用户令牌向特定用户发送通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 android 应用程序 (java),我正在使用 Firebase,对于每个注册用户,我都有一个设备令牌,如何使用他的令牌向特定用户发送通知?

I am developing an android app (java), I am using Firebase, for each registered user I have a token of the device, how can I send a notification to a specific user using his token ?

推荐答案

要向用户发送通知,唯一需要的是该用户的令牌.您可以使用 FCM 发送通知.在这里,我正在分享我的 FCM 类,可用于此目的.它使用 Okhttp3 请求,因此请确保添加其依赖项.

For sending a notification to users the only thing required is that user's token. You can send notification using FCM. Here, I'm sharing my FCM class which can be used for this purpose. It is using Okhttp3 requests, so make sure you add its dependency.

    implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.2'

添加此依赖项后,您所要做的就是使用此 FCM 类.

After adding this dependency, all you have to do is to use this FCM class.

FCMMessages.java

public class FCMMessages {

    private Context context;

    public void sendMessageSingle(Context context, final String recipient, final String title, final String body, final Map<String, String> dataMap)
    {
        this.context = context;

        Map<String, Object> notificationMap = new HashMap<>();
        notificationMap.put("body", body);
        notificationMap.put("title", title);

        Map<String, Object> rootMap = new HashMap<>();
        rootMap.put("notification", notificationMap);
        rootMap.put("to", recipient);
        if (dataMap != null)
            rootMap.put("data", dataMap);

        new SendFCM().setFcm(rootMap).execute();
    }


    public void sendMessageMulti(Context context, final JSONArray recipients, final String title, final String body, final Map<String, String> dataMap) {
        this.context = context;

        Map<String, Object> notificationMap = new HashMap<>();
        notificationMap.put("body", body);
        notificationMap.put("title", title);
        Map<String, Object> rootMap = new HashMap<>();
        rootMap.put("notification", notificationMap);
        rootMap.put("registration_ids", recipients);
        if (dataMap != null)
            rootMap.put("data", dataMap);

        new SendFCM().setFcm(rootMap).execute();
    }

    @SuppressLint("StaticFieldLeak")
    class SendFCM extends AsyncTask<String, String, String> {

        private String FCM_MESSAGE_URL = "https://fcm.googleapis.com/fcm/send";
        private Map<String, Object> fcm;

        SendFCM setFcm(Map<String, Object> fcm) {
            this.fcm = fcm;
            return this;
        }

        @Override
        protected String doInBackground(String... strings) {
            try {
                MediaType JSON = MediaType.parse("application/json; charset=utf-8");
                RequestBody body = RequestBody.create(JSON, new JSONObject(fcm).toString());
                Request request = new Request.Builder()
                        .url(FCM_MESSAGE_URL)
                        .post(body)
                        .addHeader("Authorization","key=" + StaticConfig.myMessagingAuth)
                        .build();
                Response response = new OkHttpClient().newCall(request).execute();
                return response.body().string();

            } catch (Exception e) {
                e.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(context, "Sent: " + success + "/" + (success + failure), Toast.LENGTH_LONG).show();
            } catch (JSONException e) {
                e.printStackTrace();
//                Toast.makeText(context, "Message Failed, Unknown error occurred.", Toast.LENGTH_LONG).show();
            }
        }
    }

}

确保您从您的 Firebase 项目设置中获取了 messagesAuth.要获取 messagesAuth 令牌,请按以下步骤操作:

Make sure you get the messagingAuth from your firebase project settings. To get the messagingAuth token, follow these steps:

Open Firebase Project > Project Settings > Cloud Messaging > Server key

复制服务器密钥的值并将其作为messagesAuth粘贴到您的android项目中.

Copy the value of server key and paste it as messagingAuth in your android project.

要向单个用户令牌发送通知,请使用 sendMessageSingle 方法.就像

To send a notification to single user token use sendMessageSingle method. It would be like

String user_token = "wiubd92uhe91dik-q";
String notification_title = "This is notification title";
String notification_des = "This is notification description";
new FCMMessages().sendMessageSingle(MainActivity.this, user_token, notification_title, notification_des, null);

要向多个用户令牌发送通知,请使用 sendMessageMulti 方法.就像

To send a notification to multiple user tokens use sendMessageMulti method. It would be like

ArrayList<String> user_tokens = new ArrayList<>();
user_tokens.add(token_1);
user_tokens.add(token_2);
user_tokens.add(token_3);
String notification_title = "This is notification title";
String notification_des = "This is notification description";
new FCMMessages().sendMessageMulti(MainActivity.this, new JSONArray(user_tokens), notification_title, notification_des, null);

这篇关于如何使用 Firebase 中的用户令牌向特定用户发送通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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