【发布时间】:2022-06-20 00:23:22
【问题描述】:
我正在使用 Firebase 推送通知构建 Flutter 应用。
收到消息后,我希望应用显示带有文本的弹出模式。
-
当应用程序处于前台时,弹出模式会显示 - 这有效
-
当应用程序是后台并且移动设备接收到消息时,它会显示在系统托盘中,用户单击它,应用程序打开,并找到初始消息并在弹出模式中显示给用户 - 例如. FirebaseMessaging.onMessageOpenedApp 函数 - 这行得通。
-
当应用程序在后台时,手机收到通知(并且firebase监听器正在工作,因为它使用debugPrint输出消息数据进行测试),它出现在系统托盘中,但用户选择不单击消息 - 当应用程序回到前台时,消息被忽略 - 这是一个问题。
“FirebaseMessaging.onBackgroundMessage”函数需要放置在 TOP LEVEL(任何类之外)。因此,当再次将应用程序置于前台时,如何将可能在应用程序处于后台时收到的消息中的消息数据推送到我的 App Class 以显示消息内容?我正在使用“AppLifecycleState”来检测应用程序何时返回到前台,但我无法抓取消息数据,因为它是在顶层而不是类中接收的。
请在下面查看我的代码(请参阅最后几行以了解我遇到的问题)...
//TOP LEVEL-----
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
if (message.messageId!="") {
debugPrint("Have received a background message! Will have to grab the message from here somehow if the user didn't interact with the system tray message link");
}
}
Future<void> main() async {
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
runApp(MyApp());
}
//APP CLASS-----
class MyAppextends StatefulWidget {
State<MyApp> createState() => _MyAppState();
}
//APP STATE CLASS
class _MyAppState extends State<MyApp> with WidgetsBindingObserver{
@override
void initState() {
super.initState();
_initiateNotificationForegroundListener();
_initiateInteractedMessage();
}
// This variable will tell you whether the application is in foreground or not.
bool _isInForeground = true;
//Initiate Foreground Notification Listener (works)
void _initiateNotificationForegroundListener() {
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
_handleNotificationInstruction(message);
});
}
//Initiate Background/Closed Notification Listener if user clicks the message in the system try (works)
Future<void> _initiateInteractedMessage() async {
RemoteMessage? message = await FirebaseMessaging.instance.getInitialMessage();
if (message != null) {
_handleNotificationInstruction(message);
}
// When app is in background (Stream listener)
FirebaseMessaging.onMessageOpenedApp
.listen(_handleNotificationInstruction);
}
void _handleNotificationInstruction(RemoteMessage message) {
//Create popup to display message info (works)
}
//Detect when an app moves in to the foreground
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
_isInForeground = state == AppLifecycleState.resumed;
if(_isInForeground){
/** HELP!!!
/* How can I check what message might have been received while app was in the background?? ie. the top-level _firebaseMessagingBackgroundHandler function??
**/
}
}
【问题讨论】:
标签: firebase flutter push-notification firebase-cloud-messaging