首页 > 解决方案 > Firebase Messaging:使用云功能向所有应用用户发送数据消息

问题描述

我如何向应用程序的所有用户发送消息?
使用 Web GUI,可以向应用程序的所有用户发送通知消息,因此我假设对函数执行相同操作,并且数据消息(或至少使用通知消息)也可以使用函数 - 但我找不到办法做到这一点。

我的尝试

我尝试通过调用以下方式为所有设备订阅一个主题:

FirebaseMessaging.getInstance().subscribeToTopic("all");

如果onCreate是 my FirebaseMessagingService,则发送带有云功能的消息:

exports.sendMessage = functions.database.ref("/messages/{meta}")
    .onCreate((snapshot, context) => {
        const message = snapshot._data;
        console.log("msg", message["title"]);
        // logs the correct data, therefore the event triggers
        const payload = {
            data: {
                title: message["title"]
                /* blah blah */
            },

            topic: "all"
        }

        admin.database().ref("/messages/" + context.params.meta).remove()
        return admin.messaging().send(payload)
    })

onMessageReceived不会触发(与我使用 GUI 发送通知消息时不同)。
这种方法是否可行?我错过了什么?

标签: androidfirebasepush-notificationgoogle-cloud-functionsfirebase-cloud-messaging

解决方案


我相信你需要改变的唯一部分就是结尾。你在这里不需要这部分admin.database().ref("/messages/" + context.params.meta).remove()

对于消息传递,您的代码需要类似于以下示例:

// Send a message to devices subscribed to the provided topic.
admin.messaging().send(payload)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

您需要使用 catch 来管理错误 - 这样您也将能够可视化可能导致您的问题的原因。您可以在此文档中找到更多信息:向主题发送消息

除此之外,我发现了这个不错的存储库——您可以在此处访问——其中包含一些示例和更多代码示例,介绍了如何将 Cloud Functions 与 FCM 一起使用。

让我知道这些信息是否对您有帮助!


推荐阅读