flutter - 使用 FCM 和 Flutter 通过设备发送通知
问题描述
目前我正在尝试向多个设备发送通知。我已经阅读了有关如何向设备组发送通知的文档,他们提到我需要使用registration_ids: [...]
而不是to: token
. 我还在某处读到了他们提到notification_key
的将通知发送到其他设备的内容。所以,我一直在寻找钥匙。但是,经过几天的浏览,我发现这里声明notification_key
已经弃用。所以,我想问一下你们中是否有人知道如何在不使用控制台的情况下向多个设备发送通知。
这是我发送推送通知的代码段:
try {
await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
// Uri.parse('https://fcm.googleapis.com/fcm/notification'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'key=$serverKey',
'project_id':'....',
},
body: jsonEncode(
<String, dynamic>{
'notification': <String, dynamic>{
'body': 'this is a body2',
'title': 'this is a title'
},
'priority': 'high',
'data': <String, dynamic>{
'click_action':
'FLUTTER_NOTIFICATION_CLICK',
'id': '1',
'status': 'done'
},
'registration_ids': ['fbN9aYoORhihksrTo7j5D2:APA91b......', 'fArqpgKrTJ0fL8SUKddy2F:APA91bFWf1cnVMS8.......'],
// 'to': _token,
},
),
);
} catch (e) {
print("error push notification");
}
如果我使用to
而不是 ,它可以正常工作registration_ids
,但据我所知,如果我只想为一台设备发送通知,则使用 to 。
我已经在这个问题上坚持了三天,仍然没有找到任何解决方案。他们中的大多数人都在使用控制台。你的帮助真的会让我很开心。先感谢您!
解决方案
我找到了解决方案及其工作!
var serverKey =
'AAAAUb...';
QuerySnapshot ref =
await FirebaseFirestore.instance.collection('users').get();
try {
ref.docs.forEach((snapshot) async {
http.Response response = await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=$serverKey',
},
body: jsonEncode(
<String, dynamic>{
'notification': <String, dynamic>{
'body': 'this is a body',
'title': 'this is a title'
},
'priority': 'high',
'data': <String, dynamic>{
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'id': '1',
'status': 'done'
},
'to': snapshot.data() ['tokenID'],
},
),
);
});
} catch (e) {
print("error push notification");
}
推荐阅读
- r - 每次 r 启动时,它都会在 GUI 中读取此错误消息:错误:找不到函数“libPaths”
- javascript - 如何在两个客户端上从服务器接收数据
- javascript - 直接从服务器将 csv 文件上传到 aws s3 存储桶
- sql - GPG 加密在 SSMS 作业代理中失败并在 SSIS 中成功
- python-3.x - “FusedBatchNorm 的 CPU 实现目前仅支持 NHWC 张量格式。”
- prolog - 如何让 swi prolog 解释解决方案
- node.js - 在 NodeJS 中将频繁更改的 JavaScript 对象写入文件的最有效方法是什么?
- python-3.x - 在 Python 中从外部文件调用函数
- java - 线程没有在我的程序中按顺序打印
- c# - Selenium 等到两个元素之一可见