为什么Firebase FCM通知甚至发送给邮件发件人

时间:2018-09-11 05:14:17

标签: android firebase firebase-cloud-messaging

就像whatsapp一样,如果我向其他人发送消息,他们会通过推送通知得到通知,而由于发件人而没有发送相同的推送通知。 在Firebase中,无论您是否是发件人,您都将收到甚至发送的邮件的推送通知。如果发件人是我,我如何能够向除我以外的其他人发送通知?

我正在使用Firebase Cloud功能发送推送通知。

1 个答案:

答案 0 :(得分:0)

我假设您问题中的“发件人”是指您应用程序的用户,并且您正在实现用户到用户的消息传递。通常,通过将您的应用调出到服务器来工作,然后服务器使用FCM API发送消息:

+--------+          +------------+          +----------+
| Sender |   --->   | App Server |   --->   | Receiver |
+--------+          +------------+    |     +----------+
                                      |
                                      |     +----------+
                                      +->   | Receiver |
                                            +----------+

Firebase客户端消息传递不了解正在发送消息的用户。 设备发送消息是服务器端API,具有管理访问权限。它不是以特定用户身份运行的,因此即使愿意也无法跳过该特定用户。

如果要跳过发送给特定用户的信息,则需要将有关该用户的信息传递到调用FCM API来发送消息的代码中,然后跳过用户ID在那里的令牌。假设您在节点服务器中使用Firebase Admin SDK发送消息,则代码可能如下所示:

var UIDs = ["uid1", "uid2", "uid3"];
var TOKENS = { "uid1": "token1", "uid2": "token2", "uid3": "token3" };

function sendMessage(messageText, senderUid) {
  UIDs.forEach(function(recipientUid) {
    if (recipientUid !== senderUid) {       
      var message = {
        notification: {
          title: 'Message from '+senderUid,
          body: messageText
        },
        token: TOKENS[recipientUID
      };

      admin.messaging().send(message)
        .then((response) => {
          console.log('Successfully sent message:', response);
        })
        .catch((error) => {
          console.log('Error sending message:', error);
        });
    }
  });
}