I'm trying to build an app with React Native where I need to send the notification with some custom notification sound. The Notifee shows notifications and sound in the foreground, but it does not play sound in the background. This is my App.js looks like
import React, {useEffect} from 'react';
import messaging from '@react-native-firebase/messaging';
import {
SafeAreaView,
Button,
} from 'react-native';
import notifee from '@notifee/react-native';
import {
getFCMToken,
requestUserPermission,
} from './src/NotificationHandler';
import {onDisplayNotification} from './src/BackgroundNotification';
const App = () => {
useEffect(() => {
requestUserPermission();
getFCMToken();
}, []);
useEffect(() => {
const unsubscribe = messaging().onMessage(async remoteMessage => {
onDisplayNotification();
});
return unsubscribe;
}, []);
return (
<SafeAreaView>
<Button title="Display Notification" onPress={onDisplayNotification} />
</SafeAreaView>
);
};
export default App;
I've also register the Firebase background service in Index.js which looks like
import {AppRegistry} from 'react-native';
import messaging from '@react-native-firebase/messaging';
import App from './App';
import {name as appName} from './app.json';
import {onDisplayNotification} from './src/BackgroundNotification';
import notifee, {EventType} from '@notifee/react-native';
messaging().setBackgroundMessageHandler(async remoteMessage => {
console.log('Message handled in the background!', remoteMessage);
onDisplayNotification();
});
AppRegistry.registerComponent(appName, () => App);
The onDisplayNotification
is the responsible function to handle the Notifee notification which looks like
import notifee from '@notifee/react-native';
export async function onDisplayNotification() {
console.log('ondisplaynotification');
// Request permissions (required for iOS)
await notifee.requestPermission();
// Create a channel (required for Android)
const channelId = await notifee.createChannel({
id: 'default',
name: 'Default Channel',
sound: 'customsound',
vibration: true,
vibrationPattern: [300, 500],
});
console.log('sound playing');
// Display a notification
await notifee.displayNotification({
title: 'Notification Title',
body: 'Main body content of the notification',
android: {
sound: 'customsound',
vibration: true,
vibrationPattern: [300, 500],
channelId,
// smallIcon: 'name-of-a-small-icon', // optional, defaults to 'ic_launcher'.
// pressAction is needed if you want the notification to open the app when pressed
pressAction: {
id: 'default',
},
},
});
}
The interesting point is I'm getting the log working properly. I can see that in the log Sound Playing
but the sound is not playing always. Sometimes it is playing the sound in the background and sometimes it is not playing the sound, but notification arises. Is there any way to play the custom notification sound all the time in the background even when the device is locked or the screen is off?