无法让 setBackgroundMessageHandler 工作

Can't get setBackgroundMessageHandler to work

react-native-firebase v6 中,我无法让 setBackgroundMessageHandler 在我的应用程序中工作。通知接收正常,但处理程序未执行。

我已经像guide那样做了,但没有用。

import { AppRegistry } from 'react-native';
import messaging from '@react-native-firebase/messaging';
import AsyncStorage from '@react-native-community/async-storage';
import App from './App';
import { name as appName } from './app.json';

AppRegistry.registerComponent(appName, () => App);

messaging().setBackgroundMessageHandler(async ({ data: { title, message } }) => {
    console.log('in background');
    // Save the notification locally
    const notificationList = JSON.parse(await AsyncStorage.getItem('@SM_NOTIFICATIONS')) || [];
    notificationList.push({ title, message, isRead: false });
    await AsyncStorage.setItem('@SM_NOTIFICATIONS', JSON.stringify(notificationList));
});

除了收到的通知之外什么都没发生。我希望代码将收到的通知保存在 AsyncStorage.

好的。在咨询了开发团队后,我终于弄明白了。

首先,setBackgroundMessageHandler必须在registerComponent之前调用。

其次,不发送通知数据。只发送自定义数据(静默推送)。因此,您需要使用本地通知而不是推送通知来在系统托盘中显示通知。

因为 Firebase 控制台不支持静默推送,所以我使用 FCM API v1 发送数据。这是我的例子:

POST https://fcm.googleapis.com/v1/projects/my-project/messages:send

{
    "validate_only": false,
    "message": {
        "name": "XXX",
        "data": {
            "title": "BG 2",
            "message": "BG BARU"
        },
        "topic": "C3166"
    }
}

如您所见,上面JSON中没有notification字段。