I'm trying to get the notification params in onCreate, but I only get the google.* fields.
My FCM Service:
override fun onMessageReceived(message: RemoteMessage?) {
Log.e("Push", Gson().toJson(message))
}
This will show me when app is in foreground:
{
"zza": {
"mMap": {
"google.delivered_priority": "high",
"google.sent_time": 1565619574704,
"google.ttl": 2419200,
"google.original_priority": "high",
"gcm.notification.e": "1",
"gcm.notification.title": "New meeting",
"from": "308737816494",
"gcm.notification.booking_id": "339",
"google.message_id": "0:1565619574708538%545adad5545adad5",
"gcm.notification.body": ".....",
"google.c.a.e": "1"
}
}
}
Notice "gcm.notification.booking_id": "339", this is the field I need.
When app is in background or killed, and I click the notification, I have the next code in my launcher activity:
private fun checkNotifications(intent: Intent?) {
val bookingId = intent?.getStringExtra("gcm.notification.booking_id")
Log.e("Push", "bookind id $bookingId)")
Log.e("PUSH", Gson().toJson(intent?.extras))
The problem is here that I don't get any gcm.* filters, just google.*. And of course that bookindId is null.
{
"mMap": {
"google.delivered_priority": "high",
"google.sent_time": 1565622016732,
"google.ttl": 2419200,
"google.original_priority": "high",
"from": "308737816494",
"google.message_id": "0:1565622016737416%545adad5545adad5",
"collapse_key": "com.wolfpack.planetoffinance"
}
}
Server sided code;
def options
{
notification: {
title: titles[notification.notification_type.to_sym],
body: bodies[notification.notification_type.to_sym],
booking_id: notification.booking_id
}
}
end
```def call
#other_user = other_user
response = FCM_CLIENT.send(registration_ids, options)
notification.user.devices.where(uuid: response[:not_registered_ids]).destroy_all
end
def call
#other_user = other_user
response = FCM_CLIENT.send(registration_ids, options)
notification.user.devices.where(uuid: response[:not_registered_ids]).destroy_all
end
Related
I have written this code with nodejs to send a push notification from a nodejs server to a specific user of a mobile application:
const { admin } = require("../config/Firebase");
const sendNotification = async (req, res) => {
const requestBody = req?.body;
const registrationToken = requestBody?.registrationToken; // get it from mobile app
const data = {
message: {
token: registrationToken,
notification: {
title: "Notification Title",
body: "Notification Body ",
description: "Notification description",
},
android: {
notification: {
imageUrl: "https://foo.bar.pizza-monster.png",
},
},
apns: {
payload: {
aps: {
"mutable-content": 1,
},
},
fcm_options: {
image: "https://foo.bar.pizza-monster.png",
},
},
webpush: {
headers: {
image: "https://foo.bar.pizza-monster.png",
},
},
data: {
Nick: "Mario",
Room: "PortugalVSDenmark",
},
},
};
try {
admin.messaging().send(data.message);
res.status(200).json({ notificationStatus: "success" });
} catch (error) {
console.log("Error while sending notification: ", error);
res.status(500).json({ notificationStatus: "failed" });
}
};
But it works only for android devices. So i would like to know if there a config or something like that which makes the server sends it to both iOS and android devices ?
How can I leave a push message unread, even if the app is foreground?
I am creating an application using ionic. I use push notifications using firebase cloud messaging (cordova-plugin-fcm-with-dependecy-updated) to subscribe to messages, and backend for sending.
Example backend request:
{
"headers": {
"Authorization": "key = blahblah",
"Content-Type": "application / json",
"project_id": "111111111111"
},
"json": {
"registration_ids": [
"token"
],
"time_to_live": 1200,
"data": {
"title": "title",
"body": "body",
"sound": "default",
"badge": 1,
"click_action": "FCM_PLUGIN_ACTIVITY"
}
}
}
I also tried to send the notification key instead of the date key. Tried to add to root
{
...
"android": {
"ttl": "1200s",
"priority": "high",
"notification": {
"click_action": "FCM_PLUGIN_ACTIVITY"
}
},
...
"apns":{
"headers":{
"apns-priority":10,
"apns-expiration": date('U') + 1200
},
"payload":{
"aps":{
"badge":1,
"category":"FCM_PLUGIN_ACTIVITY"
}
}
}
}
The result is the same - when the application is in the background, the push is not displayed in the tray.
How can I leave push unread, if app in foreground, and call my actions at this.fcm.onNotification().subscribe(...) only on user's click?
p.s. I tried to use cordova-plugin-local-notification, but using this caused some conflict - subscribe action doesn't fire in ios
I use ionic and cordova in my app.
I am using the plugin [cordova-plugin-firebasex] (https://github.com/dpa99c/cordova-plugin-firebasex) to receive push.
To send the push, use the following json:
{
"registration_ids": [
"token"
],
"notification":{
"title":"Ionic 4 Notification",
"body":"Notification sent from POSTMAN",
"sound":"default",
"click_action":"FCM_PLUGIN_ACTIVITY",
"icon":"notification_icon"
},
"data":{
"email":"teste#gmail.com"
},
"priority":"high"
}
For android, the "notification" field that displays a notification when the application is in the background.
If you are in foreground, you have to display a notification yourself using the plugin [cordova-plugin-local-notifications] (https://github.com/katzer/cordova-plugin-local-notifications)
My code:
constructor(private firebaseCordova: FirebaseX) {}
private initializePushApp() {
this.checkNotificationPermission(false);
this.onMessageApp();
}
checkNotificationPermission(requested) {
try {
this.firebaseCordova.hasPermission().then(hasPermission => {
if (hasPermission) {
this.getTokenApp();
} else if (!requested) {
this.firebaseCordova.grantPermission().then(value => {
this.checkNotificationPermission(true);
});
} else {
// Denied
console.log("Notifications won't be shown as permission is denied");
}
});
} catch (e) {
console.error(e);
}
}
onMessageApp() {
try {
this.firebaseCordova.onMessageReceived().subscribe(data => {
this.showNotificationCordova(data);
});
} catch (e) {
console.error(e);
}
}
showNotificationCordova(notification) {
if ('background' === notification.tap) {
// click on notification in background
alert(notification.title);
} else {
this.clickNotificationSub = this.localNotifications.on('click').subscribe(data => {
// click on notification in foreground
alert(notification.title);
});
this.localNotifications.hasPermission().then(permission => {
if (permission) {
this.localNotifications.schedule({
id: 1,
title: notification.title,
text: notification.body,
icon: notification.image ? notification.image : 'notification_icon',
});
} else {
this.localNotifications.requestPermission().then(value => {
if (value) {
this.localNotifications.schedule({
id: 1,
title: notification.title,
text: notification.body,
icon: notification.image ? notification.image : 'notification_icon',
});
} else {
console.log("Notifications won't be shown as permission is denied");
}
});
}
});
}
}
When you enter this condition 'background' === notification.tap` the notification was clicked in the background
I am using Firebase Cloud Messaging to send data notifications to other users. I'm sending a json similar to this:
{
"message":{
"to":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"title":"Portugal vs. Denmark",
"body":"great match!"
},
"data" : {
"type" : "MSG",
"id" : "abcdefg123456...."
}
}
}
And this code to receive notifications:
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
remoteMessage.notification?.let { notificacao ->
//How to read payload?
enviarNotificacao(notificacao.title ?: "", notificacao.body ?: "")
}
}
How do I read the data contained in "id" and "type"?
The id and type are both inside a data payload, to be able to read these values then try the following:
override fun onMessageReceived(remoteMessage: RemoteMessage) {
Log.d(TAG, "From: ${remoteMessage.from}")
// Check if message contains a data payload.
remoteMessage.data.isNotEmpty().let {
Log.d(TAG, "Message data payload: " + remoteMessage.data)
}
// Check if message contains a notification payload.
remoteMessage.notification?.let {
Log.d(TAG, "Message Notification Body: ${it.body}")
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
remoteMessage.data will contain both the id and type
Check here for more info:
https://firebase.google.com/docs/cloud-messaging/android/receive
You can send data this way :
{
"to": "wOAT...",
"data": {
"title": "Notification title",
"message": "Notification message",
"key1" : "value1",
"key2" : "value2",
"key3" : "value3"
}
}
and fetch data this way :
MyFirebaseMessagingService
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(p0: RemoteMessage) {
val data = p0.data
val title = data["title"]
val message = data["message"]
val key1= data["value1"]
val key2= data["value2"]
val key3= data["value3"]
showNotification(title, message, ...)
}
}
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"];
}
}
});
I am sending push notification from iOS and Android both by calling a cloud function, and in each device I am getting 5 times a single push notification. I am using parse database hosted on back4app.
Cloud code is given below:
Parse.Cloud.define("push", function (request, response) {
var query = new Parse.Query(Parse.Installation);
var userID = request.params.user;
var message = request.params.message;
var notificationType = request.params.notificationType;
var user = new Parse.User();
user.id = userID;
query.equalTo('user', user);
query.equalTo("allowPush", true);
Parse.Push.send({
where: query,
data: {
alert: message,
sound: 'default',
"type": notificationType
}
}, { useMasterKey: true });
});
Try to call reponse.success and response.error functions in the end of your cloud code function. Since your client code is not receiving the feedback if the call worked or not it is probably attempting to send again.
Parse.Cloud.define("push", function (request, response) {
var query = new Parse.Query(Parse.Installation);
var userID = request.params.user;
var message = request.params.message;
var notificationType = request.params.notificationType;
var user = new Parse.User();
user.id = userID;
query.equalTo('user', user);
query.equalTo("allowPush", true);
Parse.Push.send({
where: query,
data: {
alert: message,
sound: 'default',
"type": notificationType
}
},
{
success: function () { response.success(); },
error: function(err) { response.error(err); },
useMasterKey: true
});
});