如何向特定用户组发送Android Firebase推送通知

4
我使用Firebase创建了推送通知服务,可以向所有或单个拥有FCM ID的用户发送通知,但我不知道如何向特定用户发送通知。
此外,还没有为处理推送通知创建服务器面板。如果有任何建议,将更有帮助。

您需要通过从Web数据库中获取的JSON数据来自定义您的Web应用程序服务器所选类型,例如用户(管理员/提供者/客户)。 - Rajesh
Firebase云消息传递允许您针对特定设备上的特定应用程序(通过令牌),一组设备,所有订阅者主题或特定应用程序的所有用户进行目标定位。这些选项都没有识别单个用户。定位用户的一种方法是将每个用户映射到一个主题。在我的文章使用Firebase数据库和云消息传递在Android设备之间发送通知中采用了这种方法。 - Frank van Puffelen
感谢@FrankvanPuffelen,我会跟随你的文章。 - Anukool srivastav
阅读此博客以获取更多详细信息。https://medium.com/p/how-to-send-firebase-push-notifications-from-server-tutorial-3f3e3a78f9a5 - Developine
4个回答

5
Firebase Cloud Messaging(FCM)主题消息允许您向选择特定主题的多个设备发送消息。基于发布/订阅模型,主题消息支持每个应用程序的无限订阅,即您的组附加到特定主题,如新闻组,体育组等。请注意保留HTML标记。
FirebaseMessaging.getInstance().subscribeToTopic("news");

取消订阅:unsubscribeFromTopic("news")

从服务器端您需要为特定主题(即一组用户)设置如下:

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!",
   }
}

"/topics/news" 这将向订阅新闻主题的一组人发送通知。


据我所见,主题需要大约12个小时才能创建。有没有更快的替代方案?比如群组之类的。用户可以订阅多个主题吗? - George
1
在 Firebase 通知控制台中创建主题需要 12 小时,否则主题会立即创建,您可以使用 HTTP 请求立即发送通知。是的,用户可以订阅多个主题。 - Burhanuddin Rashid
对于群组创建,您可以选择设备组消息传递。但是,在免费版本中仅限于最多20个成员。 - Burhanuddin Rashid
谢谢你的帮助,非常有用!我会使用这些主题的。我刚刚测试过了,它像魔法一样好用 :) - George

1

我没有足够的声望来编辑Burhanuddin Rashid的答案,但我认为OP需要的是:

您可以将"to: /topics/news"替换为registration_ids

{ 

   "registration_ids" : [
   "UserInstanceToken1",
   "UserInstanceToken2"
    ]
   "data": {
    "message": "This is a Firebase Cloud Messaging Topic Message!",
    }
}

用户实例令牌可以通过 Android 中的 FirebaseInstanceId.getInstance().getToken() 获取。

阅读此博客文章以获取更多详细信息-> http://developine.com/how-to-send-firebase-push-notifications-from-app-server-tutorial/ - Developine
发送通知到注册ID只能发送给有限的用户,如果您可以为@Burhanuddin的答案增加一些知识,那么他的回答是正确的方法。 - Raj

1
在你的安卓代码中:
    public static void sendNotificationToUser(String user, final String message) {
            Firebase ref = new Firebase(FIREBASE_URL);
            final Firebase notifications = ref.child("notificationRequests");

            Map notification = new HashMap<>();
            notification.put("us

ername", user);
        notification.put("message", message);

        notifications.push().setValue(notification);
    }

创建一个节点并将以下代码放入其中:

    var firebase = require('firebase');
var request = require('request');

var API_KEY = "..."; // Your Firebase Cloud Server API key

firebase.initializeApp({
  serviceAccount: ".json",
  databaseURL: "https://.firebaseio.com/"
});
ref = firebase.database().ref();

function listenForNotificationRequests() {
  var requests = ref.child('notificationRequests');
  ref.on('child_added', function(requestSnapshot) {
    var request = requestSnapshot.val();
    sendNotificationToUser(
      request.username, 
      request.message,
      function() {
        request.ref().remove();
      }
    );
  }, function(error) {
    console.error(error);
  });
};

function sendNotificationToUser(username, message, onSuccess) {
  request({
    url: 'https://fcm.googleapis.com/fcm/send',
    method: 'POST',
    headers: {
      'Content-Type' :' application/json',
      'Authorization': 'key='+API_KEY
    },
    body: JSON.stringify({
      notification: {
        title: message
      },
      to : '/topics/user_'+username
    })
  }, function(error, response, body) {
    if (error) { console.error(error); }
    else if (response.statusCode >= 400) { 
      console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage); 
    }
    else {
      onSuccess();
    }
  });
}

// start listening
listenForNotificationRequests();

以下链接提供更多信息,它适用于许多设备:

使用Firebase数据库和云消息传递在Android设备之间发送通知


0

享受吧!

public class NotificationSenderThread implements Runnable {
private String title;
private String message;
private String senderToken;
private String recieverToken;

public NotificationSenderThread(String title, String message, String senderToken, String recieverToken) {
    this.title = title;
    this.message = message;
    this.senderToken = senderToken;
    this.recieverToken = recieverToken;
}

@Override
public void run() {
    try{
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("title", title);
        jsonObject.put("message", message);
        jsonObject.put("fcm_token", senderToken);

        JSONObject mainObject = new JSONObject();
        mainObject.put("to", recieverToken);
        mainObject.put("data", jsonObject);

        URL url = new URL("https://fcm.googleapis.com/fcm/send");
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", "key=<SERVER KEY>");
        connection.setDoOutput(true);

        Log.e("sent",mainObject.toString());
        DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
        dStream.writeBytes(mainObject.toString());
        dStream.flush();
        dStream.close();

        String line;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder responseOutput = new StringBuilder();
        while((line = bufferedReader.readLine()) != null ){
            responseOutput.append(line);
        }
        bufferedReader.close();
        Log.e("output", responseOutput.toString());
    }
    catch (Exception e){
       Log.e("output", e.toString());
        e.printStackTrace();
    }
}

}


4
你的回答不应该只是一堵代码墙,没有任何解释文字。 - svgrafov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接