应用关闭时,Firebase消息传递无法接收通知(React Native)

问题描述 投票:0回答:1

我有一个使用Firebase推送通知的应用。在我的应用程序中,我实现了2种方法:

        firebase.messaging().onMessage((message) => {        
                senName = message.data.senderName;
                senUid = message.data.senderUid;
                const notification = new 
                firebase.notifications.Notification()
                    .setNotificationId('notificationId')
                    .setTitle(message.data.title)
                    .setBody(message.data.body)
                    .android.setChannelId('channel_id_foreground')
                    .android.setSmallIcon('ic_launcher');
                firebase.notifications().displayNotification(notification)
        });

        firebase.notifications().onNotificationOpened((notificationOpen) => {
            // Get the action triggered by the notification being opened
            const action = notificationOpen.action;
            // Get information about the notification that was opened
            const notification = notificationOpen.notification;             
        });

如果我的应用程序在前台和后台运行,它将正确显示通知。如果我什么也不做,只是关闭应用程序,它就无法显示通知。

但是当在前台时,如果我点击通知它将运行onNotificationOpened方法,然后我通过滑动关闭应用程序,它仍然正常显示通知。

所以它只是在关闭/刷卡应用程序时显示通知,如果我之前已通过录制通知。

有人可以帮帮我吗?

firebase react-native push-notification
1个回答
2
投票

Android的

对于应用程序在关闭时(或在后台)获取通知,它需要注册处理这些消息的后台任务,然后在必要时打开应用程序。

要创建此任务,请使用react-native的AppRegistry.registerHeadlessTask

AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage', handler);

处理程序是返回消息处理程序的函数:

const handler = () => message => {
    // Do something with the message
}

要处理操作(在Android上),您需要另一项任务:

AppRegistry.registerHeadlessTask('RNFirebaseBackgroundNotificationAction', actionHandler);

处理程序又是这样的:

const actionHandler = () => message => {
    // Do something with message
}

要完成这一切,您需要使用以下内容更新清单:

<service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
<receiver android:name="io.invertase.firebase.notifications.RNFirebaseBackgroundNotificationActionReceiver" android:exported="true">
    <intent-filter>
        <action android:name="io.invertase.firebase.notifications.BackgroundAction"/>
    </intent-filter>
</receiver>
<service android:name="io.invertase.firebase.notifications.RNFirebaseBackgroundNotificationActionsService"/>

关于在后台设置消息传递的文档是here,对于动作是here

iOS版

在iOS上,您无法发送仅数据通知,因此您必须在通知本身(服务器端)中包含标题和文本。

如果您这样做,那么您的手机将自动显示通知,您只需处理正在打开的通知。

您还可以在显示通知时执行操作:

firebase.notifications().onNotificationDisplayed(notification => { ... })

或者当手机收到时:

firebase.notifications().onNotification(notification => { ... })

如果您想获得触发应用程序打开的通知,请使用以下命令:

firebase.notifications().getInitialNotification().then(notification => { ... })

所有这些的文档可以找到here

© www.soinside.com 2019 - 2024. All rights reserved.