我按照Flutter文档中有关如何使用新的Flutter Android嵌入式v2实现firebase_messaging的每个步骤进行了跟进。
在每个应用程序状态(前台/后台/终止或分离)下,我都可以正常接收通知。除了终止状态外,单击通知在其他状态下都可以正常工作。
在终止状态下,当我尝试单击在应用程序分离时接收到的通知时,它会打开应用程序,但是我不会在getInitialMessage函数中收到任何数据,而根据文档,我应该收到数据。此外,当我尝试通过按返回按钮离开应用程序时,某种方式应用程序在其下面显示一个额外的空活动,我不确定为什么会发生这种情况。我想摆脱它。
这些问题仅在终止状态下接收通知时才会出现。
即使在终止状态下,onBackgroundMessage监听器也可以正常工作。
main.dart:
Future<void> _backgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp();
print("Message from background : " + message.notification.body);
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
//init notification service
await NotificationService().initNotification();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(_backgroundHandler);
home_page_screen.dart: 在initState()中调用setupInteractedMessage()
Future<void> setupInteractedMessage() async {
//Terminated State
//Comes in from terminated app's notification
FirebaseMessaging.instance.getInitialMessage().then((value) => {
if (value != null)
{print("ContentAvailable : " + value.contentAvailable.toString())}
});
//Foreground state
FirebaseMessaging.onMessage.listen((event) {
String title = event.notification.title;
String body = event.notification.body;
int tag = int.parse(event.data["tag"]);
//Dont show notification if inside conversation with the sender
if (!Provider.of<ConversationBloc>(context, listen: false)
.disableNotification(tag)) {
NotificationService()
.showNotification(tag, title, body, json.encode(event.data));
} else {
soundHandler.playOnNewMessageSound();
}
print("Received in foreground");
});
//Opened from background notification trigger and handler
//It does not work if the app is detached only works in paused state
FirebaseMessaging.onMessageOpenedApp.listen((event) {
NotificationService().selectNotification(json.encode(event.data));
print("Received in background while the app is paused and not detached");
});
}
视频: https://drive.google.com/file/d/1-De9Buv6ToLB13hIat7i9uZsQOSS2XJO/view?usp=drivesdk