firebase - 应用关闭时 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 方法,然后我通过滑动关闭应用程序,它仍然正常显示通知。
因此,如果我之前录制过通知,它只会在关闭/滑动应用程序的情况下显示通知。
任何人都可以帮助我吗?
解决方案
安卓
要让应用程序在关闭时(或在后台)获得通知,它需要注册一个处理这些消息的后台任务,然后在必要时打开应用程序。
要创建此任务,请使用 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 => { ... })
所有这些的文档都可以在这里找到。
推荐阅读
- javascript - 在自定义 React Router v5 路由中调用自定义钩子会导致超出最大更新深度错误
- android - 无法将 Amplify 存储与周期性工作器一起使用
- sql - 使用oracle合并sql语句的增量加载逻辑
- node.js - Node.js 应用程序在生产中启动永无止境的进程
- arrays - 对具有相同组成的字符串进行分组
- android - Retrofit 2.0 - 添加标题不起作用
- python - 我可以创建和存储简单模拟的快照吗?
- python - 如何在python flask,Ionic 5中将Flask静态文件夹路径设置为离子生产构建文件夹“www”?
- elasticsearch - 如何编写弹性搜索查询以获取包含日期和计数的 50 个问题的列表
- ant - 如何在 Ant Task 中启动单独的进程