我正在使用此方法发送通知。
sendVoicePushNotification({required userToken,required String currentName,required String voiceUrl}) async {
try {
print("user token is: $userToken");
final body = {
"to": userToken,
"notification": {
"title": currentName,
"body": 'New voice message',
"android_channel_id": "voice",
},
'android': {
'priority': 'high',
},
'data':{
'type':'voice',
'id':'1234',
'voiceUrl': voiceUrl
}
};
var res = await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: {
'Content-Type': 'application/json;char=UTF-8',
'Authorization': 'key=' },
body: jsonEncode(body)
);
print('status: ${res.statusCode}');
print('res body: ${res.body}');
} catch (e) {
print('sendPushNotificationE: $e');
}}
并使用此代码接收后台通知。 onBackgroundMessage 方法位于应用程序的 main 方法中。
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {}
当我终止应用程序时,会收到通知。锁屏后,前 5 分钟会收到通知,但随后什么也没有。当我解锁应用程序时,再次收到通知。 我拥有所有必要的权限,例如:在后台运行、通知权限、锁定屏幕上的通知。 希望您能理解!
根据 Firebase 文档,以及我几天前的实现方式:
通过注册 onBackgroundMessage 处理后台消息 处理程序。当收到消息时,会生成一个隔离(Android 只是,iOS/macOS 不需要单独的隔离),允许您 即使您的应用程序未运行也可以处理消息。
关于您的背景消息,需要记住一些事项 处理者:
它不能是匿名函数。它必须是顶级函数 (例如,不是需要初始化的类方法)。使用时 Flutter版本3.3.0或更高版本,消息处理程序必须注释
位于函数声明的正上方 (否则它可能会在释放模式的树摇晃过程中被删除)。@pragma('vm:entry-point')
_firebaseMessagingBackgroundHandler(RemoteMessage message) async { // If you're going to use other Firebase services in the background, such as Firestore, // make sure you call `initializeApp` before using other Firebase services. await Firebase.initializeApp(); print("Handling a background message: ${message.messageId}"); } void main() { FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler); runApp(MyApp()); }
请关注这些文档以了解更多信息。