簡體   English   中英

如何將Firebase推送通知發送到特定的Android用戶組

[英]How to send firebase push notification to specific group of user for android

我已經使用Firebase創建了推送通知服務,可以將通知發送給具有FCM ID的所有或單個用戶,但是我不知道如何發送給特定用戶。

此外,不會創建服務器面板來處理推送通知處理。如果有任何建議可以幫助您。

通過Firebase Cloud Messaging(FCM)主題消息傳遞,您可以將消息發送到已選擇加入特定主題的多個設備。 基於發布/訂閱模型,主題消息支持每個應用程序的無限制訂閱,即您的組附加到特定主題(例如新聞組,體育組等)。

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"這將向訂閱新聞主題的人群發送通知

在您的android代碼中:

    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數據庫和Cloud Messaging在Android設備之間發送通知

我沒有足夠的聲譽來編輯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()

請享用 !

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM