https://blog.logrocket.com/flutter-push-notifications-with-firebase-cloud-messaging/
// For handling the received notifications
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
// Parse the message received
PushNotification notification = PushNotification(
title: message.notification?.title,
body: message.notification?.body,
);
As we can see, notification is one field in RemoteMessage structure.
and here: https://pub.dev/packages/firebase_messaging/example
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
await Firebase.initializeApp();
print('Handling a background message ${message.messageId}');
}
messageId is another field in RemoteMessage.
What other fields are in this RemoteMessage structure? I tried to find its API but failed.
Can we override it and fill our own fields?
Here is the structure of RemoteMessage. You can add your custom data to the data property of it.
const RemoteMessage(
{this.senderId,
this.category,
this.collapseKey,
this.contentAvailable = false,
this.data = const <String, dynamic>{},
this.from,
this.messageId,
this.messageType,
this.mutableContent = false,
this.notification,
this.sentTime,
this.threadId,
this.ttl});
A usual notification payload when send from the backend/cloud functions looks like this:
const payload = {
notification: {
title: title,
body: message,
},
data: {
uid,
},
webpush: {
notification: {
icon: photoURL,
},
},
android: {
notification: {
image: photoURL,
},
},
apns: {
payload: {
aps: {
"mutable-content": 1,
},
},
fcm_options: {
image: photoURL,
},
},
};
Related
I am trying to send an FCM topic message to my React Native mobile app, but they don't seem to be going through. I am using NodeJs as follows and logging the output to show that the message is getting sent successfully (no issues with android):
admin
.messaging()
.send({
data: {
title,
body,
lat: data.Location.Latitude.toString(),
lng: data.Location.Longitude.toString(),
},
android: {
priority: "high",
data: {
sound: "alert",
},
},
apns: {
payload: {
aps: {
contentAvailable: true,
},
},
headers: {
'apns-push-type': 'background',
'apns-priority': '5',
'apns-topic': 'com.xxxx',
},
},
topic: topic,
})
The react app is subscribed to the topic as follows:
useEffect(() => {
await requestUserPermissions();
messaging().subscribeToTopic(Config.INCIDENTS_TOPIC);
messaging().onMessage(sendMessage);
messaging().setBackgroundMessageHandler(sendMessage);
});
const sendMessage = (remoteMessage) => {
if (Platform.OS === 'ios') {
notificationRadiusCalculationService.sendMessage(remoteMessage);
}
};
I have set a breakpoint in the sendMessage and its never being hit.My APN was registered in firebase.
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
print('Handling a background message ${message.messageId}');
}
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
I can display background notifications with these snippet codes. But is there any way to not display some specific notification in the background?
For example I don't want to display notifications with data = {title = "call"}
from the sender device u have to send data only notification
await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'key=$serverKey',
},
body: jsonEncode(
<String, dynamic>{
'data': <String, dynamic>{
'id': '2',
'status': 'done'
},
'to': userToken,
"collapse_key": uid,
},
),
);
add conditions in your _firebaseMessagingBackgroundHandler like
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
if(message.data["title"]=="Call")
{
// show nothing
}
else
{
// show notifications
}
}
I want to send FCM to various tokens saved in the firestore document as an array with the use of firebase cloud functions. Also is it possible to send the FCM to platform-specific options in the payload. I tried a lot of examples and none worked for me. I attached the code for reference.
Tokens in firestore document:
...
let tokens2 = [];
await admin.firestore().doc(`Users/${uid}`).get().then(queryResult => {
let tokensResult = queryResult.data().tokens;
tokens2 = tokensResult;
});
let message = {
notification: {
title: title,
body: content
},
data: {
channel_id: "some_channel"
},
android: {
notification: {
notificationCount: 1
}
},
apns: {
payload: {
aps: {
badge: 42,
sound: "default"
}
}
},
token: [tokens2]
};
let response = await admin.messaging().send(message).catch(e => console.log(e));;
console.log(response);
the last error on my function console:
I also tried with sendToDevice and send multicast but no lucky
any help is welcome :)
I try to implement group notification like this android group notification and ios group notification. But I can't able to do it. I tried this flutter_local_notification plugin too. but this works only when app open. not working on foreground(onResume) and background.
void registerNotification() {
_fcm.configure(
onMessage: (Map<String, dynamic> message) {
return;
},
onResume: (Map<String, dynamic> message) {
return;
},
onLaunch: (Map<String, dynamic> message) {
return;
},
onBackgroundMessage: backgroundMessageHandler);
}
payload
const payload = {
notification: {
title: title,
body: message,
},
data: {
click_action: "FLUTTER_NOTIFICATION_CLICK",
sound: "default"
},
android: {
priority: "high",
collapse_key: userName,//tried to add collapse_key for group notification
},
apns: {
headers: {
"apns-priority": "5",
},
},
token:token,
};
SOLUTION
I saw the react-native answer for this, you have to do same thing using Flutter with firebase_messaging react native answer
If you want to submit a group, you need to subscribe to a topic, in the documentation that mentions it, you would no longer send a single token, but would instead subscribe to a topic and submit it to that topic.
I'm trying to send Push Notifications with Firebase Cloud Functions with platform specific configuration. I got following config from https://firebase.google.com/docs/cloud-messaging/send-message
var message = {
notification: {
title: '$GOOG up 1.43% on the day',
body: '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
},
data: {
channel_id: threadId,
},
android: {
ttl: 3600 * 1000,
notification: {
icon: 'stock_ticker_update',
color: '#f45342',
},
},
apns: {
payload: {
aps: {
badge: 42,
},
},
},
};
but got error for admin.messaging().sendToDevice(deviceToken, message)
Messaging payload contains an invalid "android" property. Valid properties are "data" and "notification"
Any idea what is wrong here? Or maybe some samples of proper configuration for iOS/Android platforms?
sendToDevice() is a function that uses the legacy FCM HTTP endpoint. The legacy endpoint doesn't offer platform-specific fields. In order to get that functionality, you can use the new endpoint through the send() function. You may need to update your version of the Admin SDK. You can see an example in the documentation here.
For the code you provided, for example, you would send a message like this:
let message = {
notification: {
title: '$GOOG up 1.43% on the day',
body: '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
},
data: {
channel_id: threadId,
},
android: {
ttl: 3600 * 1000,
notification: {
icon: 'stock_ticker_update',
color: '#f45342',
},
},
apns: {
payload: {
aps: {
badge: 42,
},
},
},
token: deviceToken,
};
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:', error);
});
Notice the device token is now in the message object.