Anonymous
Firebase отправляет несколько уведомлений в push-уведомлении
Сообщение
Anonymous » 05 дек 2024, 13:29
Столкнулся с проблемой: когда мое приложение находится на переднем плане, то уведомление приходит один раз, но когда мое приложение находится в фоновом режиме, то уведомление приходит два или три раза. Можете ли вы просмотреть мой код и обнаружить мою ошибку?
Вот мой код.
Код: Выделить всё
import React, {useEffect, useState} from 'react';
import {
SafeAreaView,
ScrollView,
StatusBar,
StyleSheet,
Text,
View,
} from 'react-native';
import PushNotification, {Importance} from 'react-native-push-notification';
import messaging from '@react-native-firebase/messaging';
function App(): React.JSX.Element {
const [token, setToken] = useState(null);
const backgroundStyle = {
backgroundColor: 'black',
};
useEffect(() => {
// Create notification channel
PushNotification.createChannel(
{
channelId: 'channel-id',
channelName: 'My channel',
channelDescription: 'A channel to categorise your notifications',
playSound: true,
soundName: 'custom_sound_2.mp3',
importance: Importance.HIGH,
vibrate: false,
},
() => console.log('Notification channel created'),
);
// Configure PushNotification
PushNotification.configure({
onNotification: function (notification) {
console.log('Local Notification:', notification);
},
popInitialNotification: true,
requestPermissions: true,
});
// Request Firebase notification permission
const requestPermission = async () => {
const authStatus = await messaging().requestPermission();
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL;
if (enabled) {
console.log('Authorization status:', authStatus);
}
};
requestPermission();
// Get FCM token
messaging()
.getToken()
.then(fcmToken => {
console.log('FCM Token:', fcmToken);
setToken(fcmToken);
});
// Foreground notification handler
const unsubscribeOnMessage = messaging().onMessage(async remoteMessage => {
console.log('Foreground Notification:', remoteMessage);
PushNotification.localNotification({
message: remoteMessage.notification?.body ?? 'No message body',
channelId: 'channel-id',
playSound: true,
soundName: 'custom_sound_2.mp3',
importance: 'high',
vibrate: false,
title: remoteMessage.notification?.title ?? 'No Title',
});
});
const handleBackgroundNotification = async (remoteMessage: any) => {
console.log('Background Notification:', remoteMessage);
PushNotification.localNotification({
message: remoteMessage.notification?.body ?? 'No message body',
channelId: 'channel-id',
playSound: true,
soundName: 'custom_sound_2.mp3',
importance: 'high',
vibrate: false,
title: remoteMessage.notification?.title ?? 'No Title',
});
};
// Background notification handler
messaging().setBackgroundMessageHandler(handleBackgroundNotification);
return () => {
unsubscribeOnMessage();
};
}, []);
return (
Hello From React native
{/* */}
);
}
const style = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
},
main: {
flex: 1,
backgroundColor: 'white',
},
text: {
color: 'black',
},
});
export default App;
Вот также мой файл AndroidManifest.xml.
Для получения уведомлений я использую библиотеку act-native-push-notification.
Ребята, помогите пожалуйста мне, чтобы устранить эту ошибку.
Подробнее здесь:
https://stackoverflow.com/questions/792 ... tification
1733394586
Anonymous
Столкнулся с проблемой: когда мое приложение находится на переднем плане, то уведомление приходит один раз, но когда мое приложение находится в фоновом режиме, то уведомление приходит два или три раза. Можете ли вы просмотреть мой код и обнаружить мою ошибку? [b]Вот мой код.[/b] [code]import React, {useEffect, useState} from 'react'; import { SafeAreaView, ScrollView, StatusBar, StyleSheet, Text, View, } from 'react-native'; import PushNotification, {Importance} from 'react-native-push-notification'; import messaging from '@react-native-firebase/messaging'; function App(): React.JSX.Element { const [token, setToken] = useState(null); const backgroundStyle = { backgroundColor: 'black', }; useEffect(() => { // Create notification channel PushNotification.createChannel( { channelId: 'channel-id', channelName: 'My channel', channelDescription: 'A channel to categorise your notifications', playSound: true, soundName: 'custom_sound_2.mp3', importance: Importance.HIGH, vibrate: false, }, () => console.log('Notification channel created'), ); // Configure PushNotification PushNotification.configure({ onNotification: function (notification) { console.log('Local Notification:', notification); }, popInitialNotification: true, requestPermissions: true, }); // Request Firebase notification permission const requestPermission = async () => { const authStatus = await messaging().requestPermission(); const enabled = authStatus === messaging.AuthorizationStatus.AUTHORIZED || authStatus === messaging.AuthorizationStatus.PROVISIONAL; if (enabled) { console.log('Authorization status:', authStatus); } }; requestPermission(); // Get FCM token messaging() .getToken() .then(fcmToken => { console.log('FCM Token:', fcmToken); setToken(fcmToken); }); // Foreground notification handler const unsubscribeOnMessage = messaging().onMessage(async remoteMessage => { console.log('Foreground Notification:', remoteMessage); PushNotification.localNotification({ message: remoteMessage.notification?.body ?? 'No message body', channelId: 'channel-id', playSound: true, soundName: 'custom_sound_2.mp3', importance: 'high', vibrate: false, title: remoteMessage.notification?.title ?? 'No Title', }); }); const handleBackgroundNotification = async (remoteMessage: any) => { console.log('Background Notification:', remoteMessage); PushNotification.localNotification({ message: remoteMessage.notification?.body ?? 'No message body', channelId: 'channel-id', playSound: true, soundName: 'custom_sound_2.mp3', importance: 'high', vibrate: false, title: remoteMessage.notification?.title ?? 'No Title', }); }; // Background notification handler messaging().setBackgroundMessageHandler(handleBackgroundNotification); return () => { unsubscribeOnMessage(); }; }, []); return ( Hello From React native {/* */} ); } const style = StyleSheet.create({ container: { flex: 1, backgroundColor: 'white', }, main: { flex: 1, backgroundColor: 'white', }, text: { color: 'black', }, }); export default App; [/code] [b]Вот также мой файл AndroidManifest.xml.[/b] [code] [/code] [b]Для получения уведомлений я использую библиотеку act-native-push-notification.[/b] Ребята, помогите пожалуйста мне, чтобы устранить эту ошибку. Подробнее здесь: [url]https://stackoverflow.com/questions/79254276/firebase-send-multiple-notification-in-push-notification[/url]