Flutter - Call Firebase onMessage method when the app is in background - android

The question is same as here Call onMessage method when the app is in background in flutter and I am following the thread but since there is no response, I am asking this question again.
I've connected my Flutter app with Firebase Messaging and I am receiving notification when my app is in Foreground using the Flutter Local Notifications Plugin. But I cannot receive any notification when my app is in Background
Following is my code:
// FIREBASE CONFIGURATION & HANDLING
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
debugPrint("onMessage: $message");
final notification = message['data']['notification'];
Map responseBody = convert.jsonDecode(notification);
_showNotification(
icon: responseBody['icon'],
title: responseBody['title'],
body: responseBody['body'],
);
setState(() {});
},
);
// DISPLAY NOTIFICATION - HEADS UP
Future<void> _showNotification({String icon, String title, String body}) async {
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'your channel id',
'your channel name',
'your channel description',
importance: Importance.Max,
priority: Priority.High,
ticker: 'ticker',
);
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0,
title,
body,
platformChannelSpecifics,
);
}
Can someone please guide me how can I receive notifications when my app is in Background

Resolved!!
The issue was with the format of curl calling. As per the instructions given here
Changed this:
{
"data": {
"notification": {
"title": "Notification Title",
"body": "Notification Body",
},
"click_action": "FLUTTER_NOTIFICATION_CLICK"
},
"to": "YOUR_DEVICE_TOKEN"
}
To this:
{
"data": {
"click_action": "FLUTTER_NOTIFICATION_CLICK",
"id": "1",
"status": "done",
},
"notification": {
"body": "Notification Body",
"title": "Notification Title"
},
"priority": "high",
"to": "YOUR_DEVICE_TOKEN"
}

Related

Flutter Notifications: Display WhatsApp like notification

I am trying to display notifications in my flutter app using awesome_notifications package (https://pub.dev/packages/awesome_notifications) . Below is my code.
await AwesomeNotifications().createNotification(
content: NotificationContent(
id: UniqueKey().hashCode,
groupKey: message.data["senderUid"],
channelKey: 'basic_channel',
title: message.data["title"],
body: message.data["body"],
summary: message.data["body"], // Anything you want here
notificationLayout: NotificationLayout.Messaging,
),
);
Below is my Json data
"message": {
"token": recieverFcm,
"data": {
"title": senderName,
"body": message,
"chatRoomId": chatRoomId,
"sender_profile_pic": senderProfilePic,
"senderUid": senderUid,
"click_action": "OPEN_CHAT_ROOM"
},
"android": {
"priority": "high"
},
"apns": {
"payload": {
"aps": {
"category": "OPEN_CHAT_ROOM"
}
}
}
}
This works fine and I get notifications like below.
In here it is displaying the first letter of the sender's name as the icon/profile picture. Instead, I would like to display the real photo of the sender. This profile photo is already being sent by the JSON code.
How can I do this?

How to correctly specify channel_id in FCM using cloud functions

Unfortunately, no answer yet. I am checking out postman, I hope I can use that to test quicker.
I manage to send a notification through my app, however, the notification always ends up in the silent notification of my phone, no sound, no vibration and no notification icon in the top left of the phone, only a notification in the drawer when I swipe down :(
In an attempt to fix / improve the situation I tried the following:
Create an android notification channel with id: high_importance_channel by using flutter_local_notifications package. The channel was created successful, because requesting an overview of the existing channels, showed the newly created channel (among the other channels). The new channel has importance: 5, enableVibration: true and playSound: true, so that should do the job.
Send a FCM through cloud functions with the following code:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.chatNotification = functions.firestore
.document('chats/{groupId}/chat/{chatId}')
.onCreate( async (snapshot, context) => {
const message = {
"notification": {
"title": "Message Received",
"body": "Text Message from " + fromUserName,
},
"tokens": registrationTokens,
"android": {
"notification": {
"channel_id": "high_importance_channel",
},
},
};
admin.messaging().sendMulticast(message)
.then((response) => {
console.log(response.successCount + ' messages were sent successfully');
});
}
But so far not luck, the notification still ends up in the silent notifications. What am I doing wrong?
There are 2 ways of doing it. Might work in your case.
Way 1:
var payload = {
notification: {
android_channel_id: 'AppChannel',
/*
https://stackoverflow.com/questions/62663537/how-do-i-add-a-channelid-to-my-notification
https://firebase.google.com/docs/cloud-messaging/http-server-ref#notification-payload-support
*/
title: 'Push Notification Arrived!',
body: 'Using Cloud Functions',
sound: 'default',
},
data: {
route: '/someRoute',
},
};
try {
const response = await admin.messaging().
sendToDevice(deviceTokens, payload);
console.log('Notification sent succesfully.');
} catch (err) {
console.log('Error sending Notifications...');
console.log(err);
}
Way 2:
const message = {
/*
https://firebase.google.com/docs/reference/admin/node/firebase-admin.messaging.basemessage.md#basemessagenotification
*/
notification: {
title: 'Push Notification Arrived!',
body: 'Using Cloud Functions',
},
data: {
route: '/someRoute',
},
android: {
/*
https://firebase.google.com/docs/reference/admin/node/firebase-admin.messaging.androidnotification.md#androidnotificationbodylockey
*/
notification: {
channelId: "AppChannel",
priority: 'max',
defaultSound: 'true',
},
},
token: deviceTokens,
};
// https://firebase.google.com/docs/reference/admin/node/firebase-admin.messaging.messaging.md#messagingsend
admin.messaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message, for LOVEs sake:', error);
});

Flutter Firebase notification onlunch is not working

I am using FCM service in my flutter app for push notification. onMessage and onResume are working, the problem is when I remove my app from the recent apps list. I successfully get a push notification when my app is killed but the problem is when I click on it I am not getting the access of the data payload in my flutter code. callerInfo is not being set.
Notifications are not getting delivered when the app is swiped from the background(kill mode).
JSON file
{
"notification": {
"title": "bla bla",
"body" : "bla bla",
"icon":"incoming_call",
"color": "#008080",
"click_action":"FLUTTER_NOTIFICATION_CLICK",
"tag" : "call"
},
"data": {
"caller":"caller1",
"image":"
},
"to":"#token",
"android":{
"priority":"high"
}
}
flutter config code in the initState() {}
_configureFireBaseListeners(){
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async{
//_setMessage(message);
print("onMessage: $message");
},
onLaunch: (Map<String, dynamic> message) async{
//_setMessage(message);
print("onLaunch: $message");
setState((){
_isCall=message['data']['status'];
callerInfo = message['data'];
});
},
onResume: (Map<String, dynamic> message) async{
//_setMessage(message);
print("onResume: $message");
setState((){
_isCall=message['data']['status'];
callerInfo = message['data'];
});
},
);
}

OneSignal notification to open certain activity on click

I checked the Open application on notification click in OneSignal and OneSignal Push Notification Click to open actiivty but still not answers yet. So, I'm building a news app and integrating it with OneSignal, I'm able to receive the notification and when I clicking on it I'm getting the below JSON code
OneSignal.shared.setNotificationOpenedHandler((OSNotificationOpenedResult result) {
this.setState(() {
print(
"Opened notification:
${result.notification.jsonRepresentation().replaceAll("\\n","\n")}");
});
});
JSON Response
Opened notification: {
"payload": "{
"google.delivered_priority": "normal",
"google.sent_time": 1561415365754,
"google.ttl": 259200,
"google.original_priority": "normal",
"custom": "{"a":{"id":"43682"},"i":"b0f4ef57-9556-4163-9e5c- fbcea08b4ce8"}",
"from": "800826514709",
"alert": "Test Alert",
"title": "Test Title",
"google.message_id": "0:1561415365759264%e192c215f9fd7ecd",
"notificationId": -655945385
I/flutter (30970): }",
"displayType": 2,
"shown": true,
"appInFocus": true,
"silent": null
I/flutter (30970): }
And the below code to capture the payload keys
print(result.notification.payload.jsonRepresentation());
JSON Response
{
"google.delivered_priority": "normal",
"google.sent_time": 1561415365754,
"google.ttl": 259200,
"google.original_priority": "normal",
"custom": "{"rec":{"id":"43682"},"i":"b0f4ef57-9556-4163-9e5c-fbcea08b4ce8"}",
"from": "800826514709",
"alert": "Test Alert",
"title": "Test Title",
"google.message_id": "0:1561415365759264%e192c215f9fd7ecd",
"notificationId": -655945385
}
My Question is how do I read the Key "notificationId" and "custom", I tried something like below but getting null
Map<String, dynamic> data =
json.decode(result.notification.jsonRepresentation());
print(data['custom']);
i have this solution for you.
var notificationId = result.notification.payload.rawPayload["notificationId"];
Map<String, dynamic> custom = result.notification.payload.additionalData;
Good luck :)
You can get additional data with this:
OneSignal.shared.setNotificationOpenedHandler((openedResult) async{
var additionalData = openedResult.notification.payload.additionalData;
if(additionalData != null){
if(additionalData.containsKey("myKey")){
var myValue= additionalData["myKey"];
}
}
});

Flutter firebase cloud function, playload issue

I'm using firebase cloud function for send push notification. It works but issue by default it shows badge and does not play sound when notification comes.
Below is my playload code.
var playload = {
notification: {
title: msgData.title,
body: msgData.message,
sound: 'default',
badge: '0',
click_action: 'FLUTTER_NOTIFICATION_CLICK'
},
data: {
title: msgData.title,
body: msgData.message,
sound: 'default',
badge: '0',
click_action: 'FLUTTER_NOTIFICATION_CLICK'
}
}
var options = {
priority: "high",
timeToLive: 60 * 60 * 24
};
return admin.messaging().sendToDevice(tokens, playload, options).then((response) => {
console.log('Sent to all the devices');
return response;
}).catch((err) => {
console.log(err);
return 0;
})
I have set 'sound': 'default' and badge: '0' but doesn't help me.
UPDATED:
I have tried with double quote for both keys and values but didn't work yet.
var playload = {
"notification": {
"title": msgData.title,
"body": msgData.message,
"sound": "default",
"badge": "0",
"click_action": "FLUTTER_NOTIFICATION_CLICK"
},
"data": {
"title": msgData.title,
"body": msgData.message,
"sound": "default",
"badge": "0",
"click_action": "FLUTTER_NOTIFICATION_CLICK"
}
}
Have you tried to replace your single quotes with double quotes?
From JSON.org:
A value can be a string in double quotes, or a number, or true or
false or null, or an object or an array. These structures can be
nested.
The title and the body of your message is processed before it eventually will fail which might be why it seems that your formatting is okay.
Let me know whether this has helped you.

Categories

Resources