android - 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 发送通知消息时不同)。
这种方法是否可行?我错过了什么?
解决方案
我相信你需要改变的唯一部分就是结尾。你在这里不需要这部分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 一起使用。
让我知道这些信息是否对您有帮助!
推荐阅读
- c++ - 向量int交换实现?
- maven - Maven Surefire 运行测试命令行字符串限制 (-Dtest=xyz#abc)
- firebase - Firebase 中的 BigQuery 集成反复返回 409
- html - 关于 HTML5 替代图像文件的说明
- aerospike - AEROSPIKE_ERR_INDEX_NOT_FOUND - Python 客户端
- firebase - 如何使用 id_token 通过 HTTP REST API 生成自定义令牌
- android - 我需要同步第二个库,但 IDE 告诉我他找不到它为什么以及是什么问题
- powershell - 使用 powershell 构建管道
- python - 在python中,如何求解对数方程(x*logx)
- python - S3 存储桶上的 AWS Lambda 触发器到海王星“无法为源启动新负载”