My problem is regarding the push notification using Flutter and firebase_messaging plugin
Problem:
I have integrated firebase_messaging plugin to my flutter app for push notification. I can guarantee that the setup is correct to the best of my knowledge as i am receiving push notification. The problem occurs when pushes are received only when my app is running in the background(like minimizing but available in the system memory). Pushes are not received when app is in foreground or is killed.
To provide a solution on what I have tried, I could not figure out actually needs to be done.
I have followed tutorials on this and applied every single step to overcome the problem but to no avail.
I am using nodeJS to handle the firebase-admin and serviceaccountkey file as I need device_tokens from my DB.
NodeJS
const firebase = require('firebase-admin');
const serviceAccount = require('../controller/firebase/serviceAccountKey.json');
firebase.initializeApp({
credential: firebase.credential.cert(serviceAccount)
});
//Function to actually implement the push
const pushNotificationInitiatorSubscription = (resultValue) => {
let devicesTokenString = resultValue[0]['device_token'];
const firebaseToken = devicesTokenString;
const payLoad = {
notification: {
title: 'New Subscription',
body: 'You have a new subscription to your material ' + resultValue[0]['course_name']
}
};
const option = {
priority: 'high'
};
firebase.messaging().sendToDevice(firebaseToken, payLoad, option).then(success => {
// console.log(success.results[0]['error']);
// console.log(success.results[1]['error']);
// console.log(success);
}).catch(err => {
console.log(err);
})
Flutter
import 'package:firebase_messaging/firebase_messaging.dart';
class FirebaseCloudMessage {
static FirebaseCloudMessage _instance = new FirebaseCloudMessage.internal();
FirebaseCloudMessage.internal();
factory FirebaseCloudMessage() => _instance;
final FirebaseMessaging _firebaseMessaging = new FirebaseMessaging();
configureFirebaseListeners() {
print('Here');
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print("Message $message");
// return message;
}, onLaunch: (Map<String, dynamic> message) async {
print("Message $message");
// return message;
}, onResume: (Map<String, dynamic> message) async {
print("Message $message");
// return message;
});
}
}
Help would be appreciated. Thanks
To handle messages while your application is in the foreground, listen to the onMessage stream. }); The stream contains a RemoteMessage , detailing various information about the payload, such as where it was from, the unique ID, sent time, whether it contained a notification and more.
It offers a bunch of features like for example scheduling when notifications should appear, periodically show a notification (interval-based), handle when a user has tapped on a notification when the app is in the foreground, background, or terminated, specify a custom notification sound and much more.
In the main app target, select Signing & Capabilities > All > + Capability and then search "push." Double-click on Push Notifications to enable it. Next, enable Background Modes and check Remote Notifications. Now you are ready to send notifications from the OneSignal dashboard!
If you want to disable push notifications for the user, use Notifications. setPushNotificationsEnabled(false) . When push notifications are disabled, you still can query for GetSocial Notifications via data API. To enable push notifications use Notifications.
This is the default behavior of notifications received from the firebase notification service currently. You have to manually write code if you wanna show the notification when your app is in the foreground.
Here's a demo of showing notification in flutter using flutter_local_notifications package.
NOTE: This is a really basic example of showing notifications in flutter using flutter_local_notification package. There's a lot you can configure. For a detailed explanation, visit homepage of this package or read this really good medium article
Step 1: install flutter_local_notifications package in your pubspec.yaml
Step 2: initiate FlutterLocalNotifications in initState():
@override
void initState() {
super.initState();
var initializationSettingsAndroid =
new AndroidInitializationSettings('@mipmap/ic_launcher');
var initializationSettingsIOS = new IOSInitializationSettings();
var initializationSettings = new InitializationSettings(
initializationSettingsAndroid, initializationSettingsIOS);
flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: onSelectNotification);
}
Step 3: Create a function to handle click events on the notification. This function will be called when a user will tap on the notification.
Future<dynamic> onSelectNotification(String payload) async {
/*Do whatever you want to do on notification click. In this case, I'll show an alert dialog*/
showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text(payload),
content: Text("Payload: $payload"),
),
);
}
Step 4: Write a function to show notification:
Future<void> _showNotification(
int notificationId,
String notificationTitle,
String notificationContent,
String payload, {
String channelId = '1234',
String channelTitle = 'Android Channel',
String channelDescription = 'Default Android Channel for notifications',
Priority notificationPriority = Priority.High,
Importance notificationImportance = Importance.Max,
}) async {
var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
channelId,
channelTitle,
channelDescription,
playSound: false,
importance: notificationImportance,
priority: notificationPriority,
);
var iOSPlatformChannelSpecifics =
new IOSNotificationDetails(presentSound: false);
var platformChannelSpecifics = new NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
notificationId,
notificationTitle,
notificationContent,
platformChannelSpecifics,
payload: payload,
);
}
Step 5: Call the _showNotification() function:
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
//print("Message $message");
_showNotification(1234, "GET title FROM message OBJECT", "GET description FROM message OBJECT", "GET PAYLOAD FROM message OBJECT");
return;
}
}
After this, you will be able to show notification even when your app is in the foreground. Hopefully, this will be useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With