man*_*sun 3 mongodb push-notification node.js flutter
我开发了一个flutter android 应用程序。我的数据库是MongoDB。我使用Node.js API将我的 Flutter 应用程序与 MongoDB 连接起来。我想在新数据记录进入 MongoDB 时发送推送通知。我怎样才能做到这一点?
最简单的方法是使用 Firebase Cloud Messaging。尤其是因为 Google 正在弃用以前用于 Android 的 GCM。此外,Firebase 云消息传递是免费的,可用于 iOS 和 Android。Apple 的 APN 服务也需要设置和付费开发者帐户。
如果您还没有并启用云消息传递,请创建一个 Firebase 项目。
设置您的 Node.js 服务器,以便它可以向您的 android 和 IOS 设备发送推送通知。单击“项目概述”、“设置”和“服务帐户”,然后按照说明为您的项目生成私钥并按照说明进行设置。还有 npm install "firebase-admin"。
设置 firebase 后,请参阅这些文档以了解如何发送消息。https://firebase.google.com/docs/cloud-messaging/send-message
有多种发送消息的方法。您可以直接发送消息。
用这个代码
// This registration token comes from the client FCM SDKs.
var registrationToken = 'YOUR_REGISTRATION_TOKEN';
var message = {
data: {
score: '850',
time: '2:45'
},
token: registrationToken
};
// Send a message to the device corresponding to the provided
// registration token.
admin.messaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
Run Code Online (Sandbox Code Playgroud)
如果您要发送大量通知,您还可以为设备创建要订阅的主题。文档中再次提供了更多示例。现在,如果您想知道令牌是什么,那就是下一步。
这个包将为您提供获取通信和接收您从 Node.JS 服务器发送的通知的方法。
这是一个在前端从前端设备中获取令牌的示例。
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
bool _initialized = false;
Future<void> init() async {
if (!_initialized) {
// For iOS request permission first.
_firebaseMessaging.requestNotificationPermissions();
_firebaseMessaging.configure(onMessage: (Map<String, dynamic> `enter code here`message) {
print('onMessage: $message');
Platform.isAndroid
? showNotification(message['notification'])
: showNotification(message['aps']['alert']);
return;
}, onResume: (Map<String, dynamic> message) {
print('onResume: $message');
return;
}, onLaunch: (Map<String, dynamic> message) {
print('onLaunch: $message');
return;
});
// For testing purposes print the Firebase Messaging token
String token = await _firebaseMessaging.getToken();
print("FirebaseMessaging token: $token");
_initialized = true;
}
}
Run Code Online (Sandbox Code Playgroud)
此时,您很可能会将令牌保存到 MongoDB 数据库中,并将令牌与您的用户和该特定设备相关联。当然,您还必须安装 firebase 核心和 Flutter 并进行所有必要的配置。
您仍然可以维护您的 NodeJS API 和 MongoDB 数据库,并使用免费的云消息服务将您的服务器通知推送到您的设备。
| 归档时间: |
|
| 查看次数: |
3805 次 |
| 最近记录: |