Firebase отправляет несколько уведомлений в push-уведомленииAndroid

Форум для тех, кто программирует под Android
Ответить Пред. темаСлед. тема
Anonymous
 Firebase отправляет несколько уведомлений в push-уведомлении

Сообщение Anonymous »

Столкнулся с проблемой: когда мое приложение находится на переднем плане, то уведомление приходит один раз, но когда мое приложение находится в фоновом режиме, то уведомление приходит два или три раза. Можете ли вы просмотреть мой код и обнаружить мою ошибку?
Вот мой код.

Код: Выделить всё

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. Для получения уведомлений я использую библиотеку response-native-push-notification.
Пожалуйста, помогите мне устраните эту ошибку.

Подробнее здесь: https://stackoverflow.com/questions/792 ... tification
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Android»