我正在尝试在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推送?