【问题标题】:Can't get setBackgroundMessageHandler to work无法让 setBackgroundMessageHandler 工作
【发布时间】:2020-02-23 04:41:49
【问题描述】:

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

【问题讨论】:

    标签: android react-native react-native-firebase


    【解决方案1】:

    好的。咨询了开发团队,终于搞定了这个。

    首先,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 字段。

    【讨论】:

    • "首先,setBackgroundMessageHandler 必须在 registerComponent 之前调用" 你从哪里得到的?为什么没有记录?
    • @TuanDatTran tbh 我已经忘记了原因。我想我是从反复试验中得到的。
    • 已记录在案,请查看here要设置后台处理程序,请尽早在应用程序逻辑之外调用 setBackgroundMessageHandler。
    • setBackgroundMessageHandler 在 iOS 中为您工作。当应用关闭时,它不会在我的应用中触发。
    • 那么当应用程序关闭时,您将如何收到通知?
    猜你喜欢
    • 2017-07-06
    • 1970-01-01
    • 1970-01-01
    • 2014-12-26
    • 2017-12-22
    • 2012-02-28
    • 2015-12-01
    • 2012-01-29
    • 2014-12-16
    相关资源
    最近更新 更多