FCM和flutter(Node Js后端)中的前台和后台问题



使用的依赖项:

firebase_messaging: ^10.0.1
flutter_local_notifications: ^6.0.0
firebase_core: ^1.2.1
firebase_analytics: ^8.1.2 

问题

情况1:当应用程序在后台运行但未终止或强制停止时,它不会触发方法FirebaseMessaging.onMessageOpenedApp.listen((message) {},而是触发Future<void> backgroundHandler(RemoteMessage? message) async {}

情况2:当应用程序处于强制停止的Terminated状态时,当收到通知时其未触发FirebaseMessaging.onMessage.listen((RemoteMessage? message) {});->消息是null??

源代码:

Future<void> backgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp();
print("Back ground method called");
}
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(backgroundHandler);
runApp(MyApp());
}

//Inside the Main Class//
@override
void initState() {
super.initState();
FirebaseMessaging.instance.getInitialMessage().then((message) {
print("Get Initial method called");
Flutter toast.showToast(
msg: message!.data,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 3,
backgroundColor: Colors.red,
textColor: Colors .white,
fontSize: 16.0); 
});
FirebaseMessaging.onMessage.listen((RemoteMessage? message) {
print("On Message Listener is called");
}
});
FirebaseMessaging.onMessageOpenedApp.listen((message) {
print("on Message Opened is called");
});
}

节点Js代码

var admin = require("firebase-admin");
var serviceAccount = require("xxxx Path of the json file xxxx");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
app.post('/notification',(req, res)=>{
var registrationToken='xxxxx Token xxxxx';
var message={
data:{
title:'Go Notification',
body:'Checking the app from node',
},
token:registrationToken
};

admin.messaging().send(message).then((response) => {
console.log('Successfully sent message',response);
return res.json({status:true, msg:'Notification Sent'})
}).catch((error) => {
console.log('Error occurred while send the message',error);
return res.json({status:false, msg:error})
})
}); 

我会尽力回答你的问题,但如果我错了,请纠正我,因为我也是一个新手。在您的情况1中,当应用程序不在前台时,它将调用FirebaseMessaging.onBackgroundMessage。同样的情况也发生在你的案例2中。当您的应用程序终止时,它将调用FirebaseMessaging.onBackgroundMessage而不是FirebaseMessaging.onMessage。我会给出文档的链接,也许它会对你有所帮助。

最新更新