Android前台Firebase推送通知交互失效,求排查与解决方案
Android前台推送通知无交互的问题解决方案
你的问题出在FirebaseMessaging.onMessageOpenedApp的适用场景上:这个回调只在用户点击系统通知栏中的通知、从后台/冷启动打开App时触发。而Android前台状态下,Firebase默认不会自动将推送通知展示到系统通知栏,所以根本没有可点击的通知来触发这个回调——这就是为什么iOS前台能正常工作(iOS前台Firebase会自动展示通知),但Android前台不行。
要解决Android前台的推送交互,你需要做两件事:
- 用
FirebaseMessaging.onMessage监听前台收到的推送消息 - 手动创建本地通知并添加点击跳转逻辑
具体实现步骤
- 添加依赖
在pubspec.yaml中引入flutter_local_notifications包:
dependencies: flutter_local_notifications: ^latest_version
- 初始化本地通知服务
final FlutterLocalNotificationsPlugin _localNotifications = FlutterLocalNotificationsPlugin(); Future<void> initLocalNotifications() async { const AndroidInitializationSettings androidSettings = AndroidInitializationSettings('@mipmap/ic_launcher'); const InitializationSettings initializationSettings = InitializationSettings(android: androidSettings); await _localNotifications.initialize( initializationSettings, onDidReceiveNotificationResponse: (NotificationResponse response) async { // 处理通知点击事件,跳转到指定路由 await navigatorKey.currentState!.pushNamed("/newRoute"); }, ); }
记得在App启动时调用initLocalNotifications()。
- 监听前台推送消息并展示本地通知
FirebaseMessaging.onMessage.listen((RemoteMessage event) async { if (event.notification != null) { // 构建本地通知内容 const AndroidNotificationDetails androidDetails = AndroidNotificationDetails( 'your_channel_id', // 自定义通知渠道ID 'your_channel_name', // 通知渠道名称 importance: Importance.max, priority: Priority.high, ); const NotificationDetails notificationDetails = NotificationDetails(android: androidDetails); // 展示本地通知 await _localNotifications.show( 0, // 通知ID,可自定义 event.notification!.title, event.notification!.body, notificationDetails, payload: event.data.toString(), // 可选:传递额外数据 ); } });
补充说明
- Android 8.0及以上需要创建通知渠道,你可以在初始化时或App启动时创建:
Future<void> createNotificationChannel() async { const AndroidNotificationChannel channel = AndroidNotificationChannel( 'your_channel_id', 'your_channel_name', description: 'your_channel_description', importance: Importance.high, ); await _localNotifications.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()?.createNotificationChannel(channel); }
- 保留你原来的
onMessageOpenedApp监听,用于处理后台/冷启动时点击通知的场景,这样就能覆盖所有状态的交互逻辑了。
内容的提问来源于stack exchange,提问作者Avdept
相关产品推荐
相关产品推荐

