Flutter中后台的Firebase本地通知

3
我正在尝试在Flutter中的Android中实现本地Firebase通知。按照这篇教程,我成功地设置了应用在前台时的通知。但是当应用在后台时,我看到了本地通知和由Firebase发送的原始通知(在应用前台时我并没有看到)。这是一个问题。因为我们的服务器会发送多个通知,我正在使用android_local_notifications来过滤它们,并仅通过本地通知渠道显示选定的通知。以下是我的实现:
void main() {
  // Register local notification channel
  static final AndroidNotificationChannel androidChannel =
      AndroidNotificationChannel(
    'android_local_notifications',
    'Android Local Notifications',
    description: 'Used to show foreground notifications on Android.',
    importance: Importance.max,
  );

  static final AndroidInitializationSettings initializationSettingsAndroid =
      AndroidInitializationSettings('mipmap/ic_launcher');

    await flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<
            AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(androidChannel);
    flutterLocalNotificationsPlugin.initialize(
      InitializationSettings(android: initializationSettingsAndroid, iOS: null),
    );


  // set up on background
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  runApp(MyApp());
}


/// Handle background messages by registering a onBackgroundMessage handler.
/// When messages are received, an isolate is spawned (Android only, iOS/macOS does not require a separate isolate) allowing you to handle messages even when your application is not running.
/// https://firebase.google.com/docs/cloud-messaging/flutter/receive
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  // Initialize firebase
  await Firebase.initializeApp();

  // Creates a local notification
    flutterLocalNotificationsPlugin.show(
      notificationHashCode,
      translatedTitleString,
      translatedBodyString,
      NotificationDetails(
        android: AndroidNotificationDetails(
          androidChannel.id,
          androidChannel.name,
          channelDescription: androidChannel.description,
        ),
      ),
    );
}

清单:

<receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver"
                android:exported="true" tools:replace="android:exported"/>

当应用程序在后台运行时,如何隐藏原始Firebase推送?


你也在解决同一个问题吗?你的Flutter本地通知在onBackgroundMessage处理程序中显示吗?我的没有显示,我真的很需要帮助。 - undefined
当应用程序不活动时,onbackgroundmessage甚至没有被触发。 - undefined
1个回答

0
你应该将fcm通道设置为你的本地通道,这样你就不会看到第二个通知了。

<meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="your_channel_id" />

或者你可以尝试在你的 FCM 请求体中不设置通知元素。

{ "message":{ "token":"", "data":{ "title":"title", "body":"body" } } }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接