FCM not giving a high-priority notification (heads up notification) - android

I've set my FCM Cloud Function to priority: "high" but it is still only giving a "default" priority notification (a sound + icon in the system tray).
I want a high priority where there is also a heads up notification like Facebook Messenger. Example below:
Here is my cloud function:
const admin = require('firebase-admin')
admin.initializeApp();
exports.newMatch = functions.https.onCall((data, context) => {
const user1token = data.user1token;
const user2name = data.user2name;
const user2 = data.user2;
const payload = {
notification: {
title: user2name + " says hello!",
body: "Test"
},
data: {
"user2": user2,
}
}
const options = {
priority: "high",
timeToLive: 20000
}
return admin.messaging().sendToDevice(user1token, payload, options);
});
Is it possible to get a heads up notification?
PS: I'm using a Samsung S8 phone.

Related

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);
});

How to add settings for Android in the message

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

FCM doesn't wake up android device in Flutter

I want to wake up the device after sending FCM notification.
I was able to send notifications to android devices using admin sdk in Cloud Functions. However, I cannot wake up the device while it is locked(Only sounds come). Other apps, such as Gmai, can wake up the device. Also, it works fine on iOS.
Here are the codes in Cloud Functions.
try {
const options = {
priority: "high",
};
const payload: admin.messaging.MessagingPayload = {
notification: {
title: message.title,
body: message.body,
click_action: 'FLUTTER_NOTIFICATION_CLICK',
badge: `${message.badgeNum}`,
},
};
await admin.messaging().sendToDevice(message.fcmToken, payload, options);
} catch (e) {
console.error(e.message);
throw e;
}

Firebase notifications working but not opening app on android with Ionic

I'm using Firebase notifications on my app and for some reason, the notifications will not open the app on android. I really don't have any clue what is causing this because some apps work fine and others don't.
Does anyone have any idea what would be causing this?
I use this code to send notifications to a specific device. Sometimes they open, other times they dont.
var admin = require("firebase-admin");
var Geopoint = require("geopoint");
var serviceAccount = require("./serviceaccount.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://myapp.firebaseio.com"
});
var db = admin.database();
const title = "My Test";
const body = "My Test Body";
const deepLink = "http://google.com/";
const token = "firebaseDeviceToken";
var payload = {
notification: {
title,
body,
sound: "default",
deepLink
},
data: {
title,
body,
deepLink
}
};
var options = {
priority: "high",
timeToLive: 60 * 60 * 24,
contentAvailable: true
};
console.log(payload);
return admin
.messaging()
.sendToDevice(token, payload, options)
.then(r => {
console.log(JSON.stringify({ r }));
process.exit(0);
})
.catch(err => {
console.log(JSON.stringify({ r: err }));
process.exit(1);
});

Firebase Admin SDK sendToTopic not working

I'm deploying a mobile application (for Android and iOS) through which the admin can send alert to users registered to a specific topic. To do that I'm using Realtime Database to store alerts and cloud functions to send notifications to topic.
I've the following cloud function deployed:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNewAlertNotification = functions.database.ref('/alerts').onWrite(event => {
const getValuePromise = admin.database()
.ref('alerts')
.orderByKey()
.limitToLast(1)
.once('value');
return getValuePromise.then(snapshot => {
const { text, topics, author } = snapshotToArray(snapshot)[0];
const payload = {
data: {
title: 'Avviso',
body: text,
icon: 'ic_stat_notify',
sound: 'default',
color: '#F3E03B',
tag: 'alerts',
ticker: 'Nuovo avviso',
subtitle: 'Avvisi',
author: JSON.stringify(author)
}
};
const options = {
priority: 'high',
timeToLive: 60 * 60 * 24 * 2, // 48 hours
collapseKey: 'it.bmsoftware.caliup'
// contentAvailable: true
};
if (topics.length > 1) {
let condition = '';
topics.forEach((topic, index) => {
condition += `'${topic}' in topics`
if (index < topics.length - 1) {
condition += ' || '
}
});
console.log(`Sending alert to condition '${condition}' -> ${JSON.stringify(payload)}`);
return admin.messaging().sendToCondition(condition, payload, options);
} else if (topics.length === 1) {
let topic = topics[0];
console.log(`Sending alert to topic '${topic}' -> ${JSON.stringify(payload)}`);
return admin.messaging().sendToTopic(topic, payload, options);
} else {
console.log(`No topics found`);
}
});
});
const snapshotToArray = (snapshot) => {
let result = []
if (!snapshot || !snapshot.val())
return result
snapshot.forEach((childSnapshot) => {
let item = childSnapshot.val()
item.key = childSnapshot.key
result.push(item)
})
return result
}
When I insert a new message on the realtime database, the above function fetch that message correctly and in the log section (on the firebase console) I see the correct custom log and a log that says status 'ok'.
Despite this, no notification arrives on devices. If I test the same topic from firebase console directly it works fine so devices are properly registered.
Is there something wrong with the cloud function that I'm missing?
I believe that you should uncomment // contentAvailable: true if you are sending only data payload, at least for iOS. That way you'll be able to show and trigger the notification yourself on the app code. If you want the notification to pop up without having to process the data payload, you should pass a notification object on payload.
Notification is limited to these fields tho: https://firebase.google.com/docs/reference/admin/node/admin.messaging.NotificationMessagePayload

Categories

Resources