向设备发送消息需要您调用 Firebase Cloud Messaging API 并指定 FCM 服务器密钥。顾名思义,此密钥只能在受信任的环境中使用,例如您的开发计算机、您控制的服务器或 Cloud Functions 等环境。之所以需要这样做,是因为拥有您的 FCM 服务器密钥的任何人都可以向您应用程序的所有用户发送消息。
最简单的开始方法是简单地运行curl命令或类似的命令,调用旧版FCM REST API。请参阅此处的示例:How can I send a Firebase Cloud Messaging notification without use the Firebase Console? 要发送到主题,请确保该to值类似于"/topics/your_topic"。
对于更高的生产级别,您可能需要引入服务器或使用云功能。发送消息就变成了一个多步骤的过程,例如:
有关此示例,请参阅repo中的此文件夹functions-samples。
另请参阅:
我希望这对新开发人员有所帮助。
import 'package:http/http.dart' as http;
Future<void> sendNotification(subject,title) async{
final postUrl = 'https://fcm.googleapis.com/fcm/send';
String toParams = "/topics/"+'yourTopicName';
final data = {
"notification": {"body":subject, "title":title},
"priority": "high",
"data": {
"click_action": "FLUTTER_NOTIFICATION_CLICK",
"id": "1",
"status": "done",
"sound": 'default',
"screen": "yourTopicName",
},
"to": "${toParams}"};
final headers = {
'content-type': 'application/json',
'Authorization': 'key=key'
};
final response = await http.post(postUrl,
body: json.encode(data),
encoding: Encoding.getByName('utf-8'),
headers: headers);
if (response.statusCode == 200) {
// on success do
print("true");
} else {
// on failure do
print("false");
}
}
Run Code Online (Sandbox Code Playgroud)
FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
_firebaseMessaging.subscribeToTopic("yourTopicName");
Run Code Online (Sandbox Code Playgroud)
您可以使用和订阅主题:firebase_messagingFirebaseMessaging.subscribeToTopic
FirebaseMessaging().subcribeToTopic('topic_name');
Run Code Online (Sandbox Code Playgroud)
您可以使用 Firebase 控制台或某些后端代码(例如在 Cloud Functions 中)向主题发送通知。
| 归档时间: |
|
| 查看次数: |
5823 次 |
| 最近记录: |