首页 > 解决方案 > 应用关闭时 Firebase 消息无法收到通知(React Native)

问题描述

我有一个使用 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 方法,然后我通过滑动关闭应用程序,它仍然正常显示通知。

因此,如果我之前录制过通知,它只会在关闭/滑动应用程序的情况下显示通知。

任何人都可以帮助我吗?

标签: firebasereact-nativepush-notification

解决方案


安卓

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

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

AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage', handler);

其中 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"/>

关于在后台设置消息的文档在这里,操作在这里

iOS

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

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

两个都

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

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

或者当它被电话接收时:

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

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

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

所有这些的文档都可以在这里找到。


推荐阅读