I have a code that prepares and sends a notification to a mobile application
// Create the notification
const payload = {
notification: {
title: "Title",
body: "Body",
},
};
// Options
const options = {
contentAvailable: true,
priority: 'high'
};
admin
.messaging()
.sendToDevice(tokenSnapshot, payload, options)
.then(response => {
console.warn(">> Notification sent successfully: ", response);
return response;
})
.catch(error => {
console.warn(">> Notification sent failed: ", error);
});
I would like to add here information such as:
priority: 'max'
visibility: 'public'
These are features supported in Android
It is mentioned in the documentation that it exists.
But there is nothing mentioned how to use it
Can anyone give advice?
The purpose of this is to display Notifications on your phone when it is in the background
Related
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);
});
I am dealing with a problem with IONIC and FCM. It is the following, I am sending "data" not "notifications" from my server in Node JS to my app in IONIC, I see in the console that the data is sent, but I don't know how to access it, according to the documentation, it is in Intent extras, but I have not had success with it. I could use the "notifications" that also serve me, but the problem with that is that only if you click on the push notification do you get the data ... so if the client does not click on the notification and enters the app from the background will not be able to get that data ...
My server in Node:
const options = {
priority: "high",
timeToLive: 60 * 60 * 24,
};
const message_notification = {
/*
notification: {
title: "¡Tienes un nuevo pedido!",
body: "Tienes 30 segundos para aceptar el pedido, de lo contrario será rechazado.",
sound: "default",
vibrate: 1,
Badge: 1,
click_action: "FCM_PLUGIN_ACTIVITY"
},
*/
data: {
detalles: JSON.stringify(nuevopedido)
},
};
admin
.messaging()
.sendToDevice(primeroCola.socket_id, message_notification, options)
.then((response) => {
console.log("Notificación enviada", response);
})
.catch((error) => {
console.log(error);
});
My app in ionic:
this.fcm.onNotification().subscribe((data) => {
console.log(JSON.parse(data.detalles))
});
I tried with the cordova intent web plugin in Ionic, but I can't get the FCM intent, just my project in ionic, I don't really know much about Android.
WebIntent.getIntent().then((intent) => {
console.log('Action' + JSON.stringify(intent.action));
const intentExtras = intent.extras;
if (intentExtras == null) {
console.log("No hay extras")
} else {
console.log('Extras de intent: ' + JSON.stringify(intentExtras));
}
}, (error) => {
console.log('Error getting launch intent', error);
});
Add this before of FCMPlugin.sendPushPayload(data); in onMessageReceived (file: MyFirebaseMessagingService):
FCMPlugin.setInitialPushPayload(data);
It happens that when you only send "data" without "notification" in FCM, it does not make a set of the payload (FCMPlugin.setInitialPushPayload(data)), because there is nothing to tapped, there is no notification and it cannot listen to the "notification" event because the app is closed, so there is to get the data when you open the application again (when the app is closed) in some way, then setting that when using the getInitialPushPayload in your app, you will get the data:
App in ionic:
async created() {
const payload = await this.fcm.getInitialPushPayload()
console.log(payload)
},
Now, when you open your application that was closed, you will receive the data.
I have a cloud function which executes this code to send the notification to the user, I am getting notification correctly but I want to navigate to a particular screen for that I have to add click action something like this.
clickAction: FLUTTER_NOTIFICATION_CLICK
I have tried to put this property in different lines of code but nothing seem to work, can someone please tell where should I put it exactly?
This is my index.js file!
const message = {
token: data['guestFcmToken'],
notification: {
title: `New message from ${data['hostName']}.`,
body: data['type'] === 'image' ? 'Photo' : data['lastMessage'],
},
data: {
showForegroundNotification: 'false',
screen: 'chat'
},
}
console.log('Sending message');
const response = await admin.messaging().send(message);
console.log(response);
You can add clickAction: 'FLUTTER_NOTIFICATION_CLICK' in the following way
message = {
token: data['guestFcmToken'],
notification: {
title: `New message from ${data['hostName']}.`,
body: data['type'] === 'image' ? 'Photo' : data['lastMessage'],
},
data: {
showForegroundNotification: 'false',
screen: 'chat'
},
android: {
notification: {
clickAction: 'FLUTTER_NOTIFICATION_CLICK',
},
}
};
I have a website, where I register a service-worker for the users. I save the push notification subscription info on the backend, and send push notifications at specific times of the day. Since my users live mostly in a different time-zone, I utilize a queue which can send the push at the right time.
I save the stats in the service worker through http requests, make a hop to track the url also if the user clicks the push notification. I also track, how many push notifications I try to send according to my queue consumer service.
For some reason there is a steady 33% of undelivered messages according to the service-worker statistics. For example:
lets say I send about 20.000 push notifications a day, and the 'displayed' event fires only about 12.000-14.000 times according to the service-worker.
Anyone has any idea why this could happen?
On chrome desktop every single one of tens of thousands of push notifications arrive.
On mobile devices they are not.
This implies that the fault either lies in the google-service, or the service-workers compatibility with some mobile devices
import { serviceWorkerRoutes } from 'src/route-config';
const requestParams = {
headers: {
'Content-Type': 'application/json',
},
method: 'POST'
};
self.addEventListener('install', () => {
// the service worker must be activated as soon as it's finished installing
self.skipWaiting();
});
self.addEventListener('push', (event) => {
if (event.data) {
const data = event.data.json();
const {
badge,
body,
icon,
image,
actions,
title,
url,
sent_at: sentAt,
} = data;
const options = {
badge,
body,
actions,
data: {
actions,
sentAt,
url,
},
icon,
image,
requireInteraction: true
};
event.waitUntil(self.registration.showNotification(title, options));
return fetch(serviceWorkerRoutes.measurements, {
...requestParams,
body: JSON.stringify({
indicator: 'PUSH_NOTIFICATION_DISPLAYED',
sentAt,
})
});
}
return fetch(serviceWorkerRoutes.measurements, {
...requestParams,
body: JSON.stringify({ indicator: 'PUSH_NOTIFICATION_DATA_MISSING' })
});
});
self.addEventListener('notificationclick', (event) => {
const { notification } = event;
const hasActions = event.action && notification.data && notification.data.actions;
let { url } = notification.data;
notification.close();
if (hasActions) {
const action = notification.data.actions.find((item) => item.action === event.action);
url = action ? action.url : url;
}
// eslint-disable-next-line no-undef
const promiseChain = clients.openWindow(url);
event.waitUntil(promiseChain);
return fetch(serviceWorkerRoutes.measurements, {
...requestParams,
body: JSON.stringify({
indicator: 'PUSH_NOTIFICATION_CLICKED',
action: event.action,
sentAt: notification.data && notification.data.sentAt
})
});
});
self.addEventListener('pushsubscriptionchange',
() => fetch(serviceWorkerRoutes.measurements, {
...requestParams,
body: JSON.stringify({
indicator: 'PUSH_NOTIFICATION_SUBSCRIPTION_CHANGED',
sentAt: new Date().toISOString()
})
}));
self.addEventListener('notificationclose',
(event) => fetch(serviceWorkerRoutes.measurements, {
...requestParams,
body: JSON.stringify({
indicator: 'PUSH_NOTIFICATION_CLOSED',
sentAt: event.notification.data && event.notification.data.sentAt
})
}));
I'm implementing Push Notifications on my Android Ionic 2 App with the Ionic Native FCM
When I'm receiving a notification in the foreground it works, but when I'm receiving a notification in the background and if I clicked on it, nothing happens.
app.component.ts
firebaseInit(){
//Firebase
this.fcm.subscribeToTopic('all');
this.fcm.getToken()
.then(token => {
console.log(token);
this.nativeStorage.setItem('fcm-token', token);
});
this.fcm.onNotification().subscribe(
data => {
console.log("NOTIF DATA: " + JSON.stringify(data));
if(data.wasTapped){
this.nav.push(MemoViewPage, {memo: {_id: data.memo_id}})
console.info('Received in bg')
}else{
let alert = this.alertCtrl.create({
title: data.subject,
message: "New memorandum",
buttons: [
{
text: 'Ignore',
role: 'cancel'
},
{
text: 'View',
handler: () => {
this.nav.push(MemoViewPage, {memo: {_id: data.memo_id}})
}
}
]
});
alert.present();
console.info('Received in fg')
}
});
this.fcm.onTokenRefresh()
.subscribe(token => {
console.log(token);
})
}
The if(data.wasTapped) condition doesn't go off once I clicked the notification from the system tray.
EDIT
The app opens but only in the Home Page not to the designated page that I set which is this.nav.push(MemoViewPage, {memo: {_id: data.memo_id}})
I also cannot receive notifications when the app is killed or not running.
you could use push plugin instead of FCM.
this.push.createChannel({
id: "testchannel1",
description: "My first test channel",
importance: 3
}).then(() => console.log('Channel created'));
and then you could use pushObjects to specify the needs for your notification like sound, ion etc.
const options: PushOptions = {
android: {},
ios: {
alert: 'true',
badge: true,
sound: 'false'
},
windows: {},
browser: {
pushServiceURL: 'http://push.api.phonegap.com/v1/push'
}
};
After that it is easy for you to receive notifications whether you are using the app or not
const pushObject: PushObject = this.push.init(options);
pushObject.on('registration').subscribe((registration: any) => this.nativeStorage.setItem('fcm-token', token));
pushObject.on('notification').subscribe((notification: any) => console.log('Received a notification', notification));
you could use the option of forceShow:true in the pushObject init for the app to show the notification whether you are using the app or not.
And once you clicked the notification the notification payload is received by the app with the app home page set as default.