我有一个flutter应用程序,在某些情况下,管理员用户可以保存一个发布。
现在,我希望所有用户在发布该出版物时都能收到通知(包括标题、描述等(
我怎么能用firebase消息做到这一点?
我已经写了这段代码,如果我去firebase控制台并生成一个示例通知,我会正常收到:
class PushNotificationsManager {
PushNotificationsManager._();
factory PushNotificationsManager() => _instance;
static final PushNotificationsManager _instance = PushNotificationsManager._();
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
Future<void> init() async {
if(Platform.isIOS){
_firebaseMessaging.requestNotificationPermissions(IosNotificationSettings());
}
_firebaseMessaging.configure(
// Called when the app is in the foreground and we receive a push notif.
onMessage: (Map<String, dynamic> message) async {
print("onMessage: ${message}");
print(message['notification']['body']);
},
// Called when the app has been closed completely and its opened
// from the notification directly
onLaunch: (Map<String, dynamic> message) async {
print("onMessage: ${message}");
},
// Called when the app is in the background and its opened from the notif
onResume: (Map<String, dynamic> message) async {
print("onMessage: ${message}");
},
);
}
总之,当管理员创建新发布时,我如何向所有用户生成通知(创建标题和描述(,而不去firebase控制台手动生成它?
- 我正在使用
firebase_messaging: ^7.0.3
更新我试过这样做:
Future sendNotification() async {
final String url = 'https://fcm.googleapis.com/fcm/send';
var token = await _firebaseMessaging.getToken();
var data;
data='{"notification": {"body": "this is a body", "title": "this is a title"}, "priority": "high", "data": {"click_action": "FLUTTER_NOTIFICATION_CLICK"}, "to": "${token}"}';
final response = await http.post(
url,
headers: <String, String>{"Content-Type": "application/json", "Keep-Alive" : "timeout=5", "Authorization" : "key=${mykey}"},
body: data
);
print(response.body);
}
在我将事件保存在firebase中的方法中调用它只会向我的手机显示通知,而不是向每个手机显示通知。有办法以这种形式做到这一点吗?
您可以使用云函数来实现这一点。创建发布时从应用程序调用函数,或者让云函数侦听新文档。有关一些想法,请参阅此Medium帖子:https://medium.com/@jerinamathews/send-firebase-cloud-messaging-fcm-to-a-topic-using-cloud-function-when-realtime-database-value-fa78fa758549
更新
根据您的更新,我建议您考虑使用"主题",而不是特定的令牌(仅适用于一台设备(。要使用主题,您需要确保所有用户在打开应用程序时自动订阅所选主题(他们每次都可以订阅同一主题,不会产生负面影响(。FCM针对该主题维护订阅的设备令牌列表。
我还没有通过http帖子使用主题,所以我不能确认这是可能的,但我假设如果你可以发送到令牌,你必须能够发送到主题。