在 React Native Cloud Messaging、安静和后台模式下,会出现两个通知(一个来自 Firebase,另一个来自 Notifee)。当我单击 notifee 通知应用程序时,未打开,但如果单击 firebase 通知应用程序打开,也可以重定向特定屏幕。我如何将其实现到notifee通知中。
========这是我的onDisplayNotification(notifee)函数=======
export async function onDisplayNotification(data:any) {
// Request permissions (required for iOS)
if (Platform.OS === 'ios') {
await notifee.requestPermission();
}
// Create a channel (required for Android)
const channelId = await notifee.createChannel({
id: data?.data?.channel_id,
name: data?.data?.channel_name,
sound: data?.data?.sound_name,
// importance: AndroidImportance.HIGH,
});
// Display a notification
await notifee.displayNotification({
title: data?.notification.title,
body: data?.notification.body,
android: {
smallIcon: 'ic_launcher',
channelId,
color: BlueColor,
},
});
}
=========这是我在主屏幕中调用的 noficationListner 函数。=====
export async function notificationListner() {
//=========== Foreground state messages(when user using app open stage)===========
const unsubscribe = messaging().onMessage(async remoteMessage => {
console.log('A new FCM message arrived!', remoteMessage);
//============= showing notification on notifee ===============
await onDisplayNotification(remoteMessage);
});
//=========== Foreground state messages(when user using app open stage)==============
messaging().onNotificationOpenedApp(remoteMessage => {
console.log(
'Notification caused app to open from background state:',
remoteMessage.notification,
);
// setTimeout(() => {
// NavigationService.navigate('Menu')
// }, 1200)
// navigation to specific screen
// if (!!remoteMessage?.data && remoteMessage?.data?.redirect_to == "Menu") {
// setTimeout(() => {
// NavigationService.navigate("Menu", { data: remoteMessage?.data })
// }, 1200)
// }
});
// Check whether an initial notification is available
messaging()
.getInitialNotification()
.then(remoteMessage => {
if (remoteMessage) {
console.log(
'Notification caused app to open from quit state:',
remoteMessage.notification,
);
}
});
return unsubscribe;
}
============这是我调用index.js的后台处理程序============
messaging().setBackgroundMessageHandler(async remoteMessage => {
await onDisplayNotification(remoteMessage);
console.log('Message handled in the background!', remoteMessage);
});
我以这种格式发送通知:
{
"registration_ids":[
device-tokens......
],
"notification":{
"body":"Test notificaton body",
"title":"Test notification title!"
},
"data": {
"channel_id": "demo-channel",
"channel_name": "demo-channel",
"sound_name": "default"
}
}
关于 消息类型的 Firebase 文档有这样的说法:
使用 FCM,您可以向客户端发送两种类型的消息:
- 通知消息,有时被认为是“显示消息”。这些由 FCM SDK 自动处理。
- 数据消息,由客户端应用程序处理。
因此,当应用程序处于后台且消息具有
notification
属性时消息到达时,系统将显示该通知。无法配置您的代码来显示此通知。
如果您想始终自己处理消息的显示,则应该不发送
notification
消息而只发送data
消息。您当然可以在 data
消息中放入相同的值,以便您的代码可以从那里获取它们。