Firebase custom notification sound not playing - android

I'm working with Firebase Cloud Messaging, sending notifications from mongoDB to react-native application using react-native-push-notification.
Notification is working, but I can't play the custom notification I added in my android app in /res/raw folder.
My code:
const message = {
"to": userFinded.deviceToken,
"notification": {
"title": 'Body test',
"color": '#ff9d00',
"sound": 'my_sound', //Not working
},
};
FCM Documentation
I also tried to follow the documentation of react-native-push-notification and did this:
PushNotification.localNotification({
/* Android Only Properties */
channelId: 'fcm_fallback_notification_channel', // (required) channelId, if the channel doesn't exist, notification will not trigger.
soundName: 'my_sound.mp3', // (optional) Sound to play when the notification is shown. Value of 'default' plays the default sound. It can be set to a custom sound such as 'android.resource://com.xyz/raw/my_sound'. It will look for the 'my_sound' audio file in 'res/raw' directory and play it. default: 'default' (default sound is played)
});
PushNotification.createChannel(
{
channelId: 'fcm_fallback_notification_channel', // (required)
channelName: 'My channel', // (required)
soundName: 'my_sound.mp3', // (optional) See `soundName` parameter of `localNotification` function
});
I tried different versions:
soundName: 'my_sound.mp3';
soundName: 'my_sound';
soundName: 'android.resource://com.xyz/raw/my_sound';
soundName: 'android.resource://com.seeed/raw/my_sound';
Sometimes the notification sound is the default one, sometimes I don't have any sound.
Any help please?

you need to send android_channel_id also
like this
const message = {
"to": userFinded.deviceToken,
"notification": {
"title": 'Body test',
"color": '#ff9d00',
"sound": 'my_sound.mp3',
"android_channel_id": "fcm_fallback_notification_channel"
},

Related

Flutter: How to define notification channel in firebase_messaging package?

I am sending this json to cloud messaging (with proper headers) and want to get notification on my device, but it does not appear on my phone. I think that maybe i am missing channel id initialization for Android ?
*Additional info
If i send "notification" payload with title or body it is receiving, but i dont want to use "notification" payload. I want to have "data" payload only
{
"to" : "my device token",
"mutable_content" : true,
"content_available": true,
"data" : {
"content": {
"id": 100,
"channelKey": "basic_channel",
"title": "Huston!\nThe eagle has landed!",
"body": "A small step for a man, but a giant leap to Flutter's community!",
"notificationLayout": "BigPicture",
"largeIcon": "https://media.fstatic.com/kdNpUx4VBicwDuRBnhBrNmVsaKU=/full-fit-in/290x478/media/artists/avatar/2013/08/neil-i-armstrong_a39978.jpeg",
"bigPicture": "https://www.dw.com/image/49519617_303.jpg",
"showWhen": true,
"autoCancel": true,
"privacy": "Private"
},
"actionButtons": [
{
"key": "REPLY",
"label": "Reply",
"autoCancel": true,
"buttonType": "InputField"
},
{
"key": "ARCHIVE",
"label": "Archive",
"autoCancel": true
}
]
}
}
In order to define a notification channel you have to go to your AndroidManifest.xml and within the application component add this meta:
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel_id"/>
then in your strings.xml file put the channel id like this:
<string name='default_notification_channel_id'>Channel ID</string>
After doing this, you can define your channel id in the FCM Console.
As simple as this. Just put your android channel name here below and it works with a charm:
"notification": {
"body": "Test notification",
"title": "Test Test Test",
"click_action": "FLUTTER_NOTIFICATION_CLICK",
"sound": "your_custom_sound"
"android_channel_id": "channel_id_youcreated",
},
'to':
"",
},
Sound file name is not necessary in the above given notification payload if you assigned that sound to your notification channel thru MainActivity.kt or java file. However, it is necessary for older Android versions as they will use the sound file directly. Put your file inside res/raw folder.

React-native: permission to allow audio in Android

How do I give permission to allow audio in Android app without going to settings of phone?
I am using push notification with firebase cloud message, when there is received notification but no notification sound. If I go to phone's settings and turn on notifications for app then get an audio notification
Have a try by creating a custom notification channel using the react-native-push-notification npm package.
Create an android notification channel with your requirements like sound, notification importance, etc.
For example:
PushNotification.createChannel(
{
channelId: "channel-id", // (required)
channelName: "My channel", // (required)
channelDescription: "A channel to categorise your notifications", // (optional) default: undefined.
playSound: false, // (optional) default: true
soundName: "default", // (optional) See `soundName` parameter of `localNotification` function
importance: 4, // (optional) default: 4. Int value of the Android notification importance
vibrate: true, // (optional) default: true. Creates the default vibration patten if true.
},
(created) => console.log(`createChannel returned '${created}'`) // (optional) callback returns whether the channel was created, false means it already existed.
);
and add the notification channel-id name in the firebase.json to receive notification from firebase cloud messaging.
Like:
// <projectRoot>/firebase.json
{
"react-native": {
"messaging_android_notification_channel_id": "channel-id"
}
}
Check out the official docs for more information.
https://github.com/zo0r/react-native-push-notification

react-native-push-notification custom sound not working when android app is killed

I have been working on adding custom sounds to push notifications for a react-native app using firebase-admin version ^9.2.0 and react-native-push-notification version ^5.1.0.
The reason why I haven't upgraded to the latest version of react-native-push-notification is because custom sounds do not seem to work even with proper channel configuration. We are also using expo, which appears to be causing a startup error when using version 7+.
I have two mp3 files called regular.mp3 and mass.mp3. The firebase functions that send the push notifications send the message using the common data object, but also platform-specific fields for push notification sounds:
admin.messaging().send({
data: {
title,
body,
lat: data.Latitude.toString(),
lng: data.Longitude.toString(),
notificationType: data.NotificationType.toString(),
},
notification:{title,body},
apns:{
payload:{
aps:{
alert:{
title,
body,
},
sound: data.NotificationType === 1 ? "mass.mp3" : "regular.mp3",
},
},
},
android: {
priority: "high",
data: {
sound: data.NotificationType === 1 ? "mass" : "regular",
},
notification: {
sound: data.NotificationType === 1 ? "mass" : "regular",
},
},
topic: topic,
})
From my understanding, the data field under android does contain the payload that will be added to the root-level data object when the app is killed and receive the notification. The plugin's source also seems to be using that exact data field to set the notification sound (in RNReceivedMessageHandler.java):
JSONObject data = getPushData(notificationData.get("data"));
if (data != null) {
if (!bundle.containsKey("message")) {
bundle.putString("message", data.optString("alert", null));
}
if (!bundle.containsKey("title")) {
bundle.putString("title", data.optString("title", null));
}
if (!bundle.containsKey("sound")) {
bundle.putString("soundName", data.optString("sound", null));
}
if (!bundle.containsKey("color")) {
bundle.putString("color", data.optString("color", null));
}
Here is what I got so far:
custom sounds work great when the app is in foreground
custom sounds work great when app is in background
default sound plays when app is killed
Here is the code currently in place to manage the notifications:
In index.ts:
PushNotification.configure({
// (optional) Called when Token is generated (iOS and Android)
onRegister: function(token) {
console.log("TOKEN:", token);
},
// (required) Called when a remote is received or opened, or local notification is opened
onNotification: function(notification) {
console.log("NOTIFICATION:", notification);
// process the notification
// (required) Called when a remote is received or opened, or local notification is opened
//notification.finish(PushNotificationIOS.FetchResult.NoData);
},
// (optional) Called when Registered Action is pressed and invokeApp is false, if true onNotification will be called (Android)
onAction: function(notification) {
console.log("ACTION:", notification.action);
console.log("NOTIFICATION:", notification);
// process the action
},
// (optional) Called when the user fails to register for remote notifications. Typically occurs when APNS is having issues, or the device is a simulator. (iOS)
onRegistrationError: function(err) {
console.error(err.message, err);
},
// IOS ONLY (optional): default: all - Permissions to register.
permissions: {
alert: true,
badge: true,
sound: true,
},
popInitialNotification: true,
requestPermissions: true,
});
In App.js
CreateIncidentPushNotification=(remoteMessage)=>{
const {data} = remoteMessage;
PushNotification.localNotification({
title: data.title,
message: data.body,
playSound: true,
soundName: data.notificationType === "1" ? "mass" : "regular",
});
}
I was wondering if anyone else had an idea about what could be going on. The notification still manages to get to my device even when the app is killed, which is great. The only missing part is the sound.
Okay so I finally got it working. I had to add the following to my manifest file and comment a receiver:
<meta-data android:name="com.dieam.reactnativepushnotification.notification_channel_name"
android:value="my-channel"/>
<meta-data android:name="com.dieam.reactnativepushnotification.notification_channel_description"
android:value="my channel"/>
<!-- Change the value to true to enable pop-up for in foreground (remote-only, for local use ignoreInForeground) -->
<meta-data android:name="com.dieam.reactnativepushnotification.notification_foreground"
android:value="false"/>
<!-- Change the value to false if you don't want the creation of the default channel -->
<meta-data android:name="com.dieam.reactnativepushnotification.channel_create_default"
android:value="true "/>
<!-- Change the resource name to your App's accent color - or any other color you want -->
<meta-data android:name="com.dieam.reactnativepushnotification.notification_color"
android:resource="#color/white"/> <!-- or #android:color/{name} to use a standard color -->
<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationActions" />
<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
<!-- <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver> -->
Then, I had to use channels in order to get the sounds working in foreground, background, and when the app is killed. As you can see, I created a custom channel in my manifest file and activated the default channel as well. I HAD to activate the default channels because I have two notification types that require different sounds. Using a single channel was NOT WORKING.
Once the manifest file has been updated, I modified the firebase functions (using firebase-admin to do the following:
admin.messaging().send({
data: {
title,
body,
lat: data.Latitude.toString(),
lng: data.Longitude.toString(),
notificationType: data.NotificationType.toString(),
},
notification:{title,body},
apns:{
payload:{
aps:{
alert:{
title,
body,
},
sound: data.NotificationType === 1 ? "mass.mp3" : "regular.mp3",
},
},
},
android: {
priority: "high",
data: {
sound: data.NotificationType === 1 ? "mass" : "regular",
channelId: data.NotificationType === 1 ? "my-channel" : "fcm_fallback_notification_channel",
},
notification: {
sound: data.NotificationType === 1 ? "mass" : "regular",
channelId: data.NotificationType === 1 ? "my-channel" : "fcm_fallback_notification_channel",
},
},
topic: topic,
})
.then((response) => {
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
Firebase was now aware of the two channels I was using. I then moved to the application code and handled the local notification like this:
PushNotification.localNotification({
title: data.title,
message: data.body,
playSound: true,
soundName: data.notificationType === "1" ? "mass" : "regular",
channelId: data.notificationType === "1" ? "my-channel" : "fcm_fallback_notification_channel"
});
I also activated both onMessage and setBackgroundMessageHandler handlers of the react-native-push-notification package:
messaging().onMessage(this.sendMessage);
messaging().setBackgroundMessageHandler(this.sendMessage);
Where this.sendMessage is responsible to call the localNotification call mentioned above.
By the way, I am stil getting duplicated notifications when the app is in background, so this is purely a fix for the sounds.
UPDATE:
removing the setBackgroundMessageHandler removed the duplicates!!!! :)
Peace!

React Native Push Notifications with react-native-fcm

I'm using this library.
I'm attempting to get push notifications to display in the notifications tray on my Nexus 5 (android 6.0.1). Using React Native 0.42, React Native CLI 2.0.1. I'm developing on Ubuntu 14.04.
I'm using firebase. I go into my console > notifications > send a message > specific device (which I get from remote debugging console.log, below).
I am logging notifications, as you can see in code, and they do get to my device, as I can see them in the logs.
But, I don't know how to display them in the notifications tray. Looking through the docs and searching forums, it seems they should show up by default.
componentDidMount() {
FCM.requestPermissions(); // for iOS
FCM.getFCMToken().then(token => {
console.log(token)
// store fcm token in your server
});
this.notificationListener = FCM.on(FCMEvent.Notification, async (notif) => {
console.log(notif)
});
});
It seems that "custom_notification" is required to display the notification in the top tray. I added this to my payload:
"custom_notification": {
"body": "test body",
"title": "test title",
"color":"#00ACD4",
"priority":"high",
"icon":"ic_notif",
"group": "GROUP",
"id": "id",
"show_in_foreground": true
}
So, I think the app must receive the notification, parse out the data, and add this custom_notification parameter.
How about the following in your constructor:
FCM.requestPermissions(); // for iOS
FCM.getFCMToken().then(token => {
console.log(token)
// store fcm token in your server
});
this.notificationListener = FCM.on(FCMEvent.Notification, async (notif) => {
// do some component related stuff
console.log(notif);
//alert(notif.fcm.body);
FCM.presentLocalNotification({
id: "UNIQ_ID_STRING", // (optional for instant notification)
title: "My Notification Title", // as FCM payload
body: notif.fcm.body, // as FCM payload (required)
sound: "default", // as FCM payload
priority: "high", // as FCM payload
click_action: "ACTION", // as FCM payload
badge: 10, // as FCM payload IOS only, set 0 to clear badges
number: 10, // Android only
ticker: "My Notification Ticker", // Android only
auto_cancel: true, // Android only (default true)
large_icon: "ic_launcher", // Android only
icon: "ic_launcher", // as FCM payload, you can relace this with custom icon you put in mipmap
big_text: "Show when notification is expanded", // Android only
sub_text: "This is a subText", // Android only
color: "red", // Android only
vibrate: 300, // Android only default: 300, no vibration if you pass null
tag: 'some_tag', // Android only
group: "group", // Android only
picture: "https://google.png", // Android only bigPicture style
ongoing: true, // Android only
my_custom_data: 'my_custom_field_value', // extra data you want to throw
lights: true, // Android only, LED blinking (default false)
show_in_foreground: true // notification when app is in foreground (local & remote)
});
});
FCM.subscribeToTopic('test_topic');

Cordova PushPlugin not working when app is in foreground

I'm using Cordova 3.5.0-0.2.6 to cerate an Android application and using PushPlugin 2.2.1 to push notifications.
Everything works fine and get the notifications in my droid notifications bar when the app is in background, but when it's in foreground nothing happens when it get the notification. Wanted to make it play a sound or even show a popup alert to let the user know he has a new notification. Copied the example code from the plugin's github page (https://github.com/phonegap-build/PushPlugin) but it isn't working. The corresponding part of the code is this:
case 'message':
// if this flag is set, this notification happened while we were in the foreground.
// you might want to play a sound to get the user's attention, throw up a dialog, etc.
if (e.foreground)
{
// on Android soundname is outside the payload.
// On Amazon FireOS all custom attributes are contained within payload
var soundfile = e.soundname || e.payload.sound;
// if the notification contains a soundname, play it.
// playing a sound also requires the org.apache.cordova.media plugin
var my_media = new Media("/android_asset/www/"+ soundfile);
my_media.play();
}
else
{ // otherwise we were launched because the user touched a notification in the notification tray.
window.location = 'iframe.html?url=' + e.payload.url;
if (e.coldstart) {
//$("#app-status-ul").append('<li>--COLDSTART NOTIFICATION--' + '</li>');
} else{
//$("#app-status-ul").append('<li>--BACKGROUND NOTIFICATION--' + '</li>');
}
}
Not sure where the beep.wav file should be placed, I placed it into the www folder, but I'm 100% sure that's the place to put it.
Any one had this problem before? Any idea what I might be missing here?
Thanks,
Luciano
For android please add property "forceShow": "true" and it should work..
example code is below:
var push = PushNotification.init({
"android": {
"senderID": "xxxxxxxxx",
"forceShow": "true",
"icon": "icon",
"sound": true,
"vibration": true,
"badge": true
},
"browser": {
},
"ios": {
"senderID": "xxxxxxxxx",
"icon": "icon",
"gcmSandbox": true,
"sound": true,
"vibration": true,
"badge": true
},
"windows": {}
});
but when it's in foreground nothing happens when it get the notification
This is the default behavior of PushPlugin. It creates a notification and the associated sound only when the application is in the background or closed.
Wanted to make it play a sound or even show a popup alert to let the user know he has a new notification.
The easiest solution would be to use Cordova Plugin Dialogs. All you would have to do is:
switch( e.event )
{
case 'message':
if (e.foreground) {
navigator.notification.beep(1);
}
.
.
}
Note that this beep will be the message tone configured by the user on his/her device.
Not sure where the beep.wav file should be placed, I placed it into the www folder
Not sure either, but I think it is the www directory too.
See also: Android won't play push sound while app not running

Categories

Resources