Flutter中后台的Firebase本地通知

kupeojn6  于 2023-11-21  发布在  Flutter
关注(0)|答案(1)|浏览(173)

我正在尝试在Android中使用Flutter在后台实现本地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推送?

enyaitl3

enyaitl31#

您应该将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" } } }

相关问题