Reputation: 670
I am trying to implement local Firebase notifications in background in Android with Flutter.
Following this tutorial, I was able to get my notifications successfully set up when the app is in foreground. But while the app is in background, I do see the local notifications, but also the original notifications sent by Firebase (which I do not see while the app is in foreground).
This is a problem. Since our server sends multiple notifications, and I am implementing android_local_notifications to filter through them, and show only selected ones though local notification channel.
This is my implementation:
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,
),
),
);
}
Manifest:
<receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver"
android:exported="true" tools:replace="android:exported"/>
How do I get to hide the original Firebase pushes while the app is in background?
Upvotes: 4
Views: 1359
Reputation: 1
You should set the fcm channel to your local channel than you wont see the second notification
<meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="your_channel_id" />
or you can try not to set notification element in your fcm request body
{ "message":{ "token":"", "data":{ "title":"title", "body":"body" } } }
Upvotes: 0