首页 > 解决方案 > 应用程序在后台时无法正确显示通知(React Native)

问题描述

我有一个使用 Firebase 推送远程通知的应用程序,一个客户端发送如下通知消息:

            body: JSON.stringify({
                'to' : 'token',
                'notification' : {
                    'title' : ' ' + this.currentUser.email + ' send you a message !',      
                    'body' : text
                },
                'data': {
                    'senderName' : this.currentUser.email,
                    'senderUid': this.currentUser.uid 
                }

            })

和一个客户端实现接收通知的方法:

           firebase.notifications().onNotification((notification) => {
                    const showNotification = new firebase.notifications.Notification()
                        .setNotificationId('notificationId')
                        .setTitle(notification.title)
                        .setBody(notification.data.text)
                        .android.setChannelId('channel_id_foreground')
                        .android.setSmallIcon('ic_launcher');
                    firebase.notifications().displayNotification(showNotification)
            });

当我的应用程序在前台运行时,通知正常显示,但在后台时,它可以在通知托盘中接收,但不会将该通知显示到设备的屏幕上。




这是通知显示的方式:

问题




我希望通知可以显示如下:

正确的


补充:如果我通过滑动关闭应用程序并发送通知,我的应用程序将崩溃。


任何人都可以帮助我吗?

标签: firebasereact-nativepush-notificationfirebase-cloud-messaging

解决方案


RN Firebase 文档中所述,当您的应用程序在后台或关闭时,通知由操作系统处理和显示,因此永远不会调用您的 onNotification() 方法,因此永远不会设置通知通道。根据android developer docs,没有频道的通知不会出现。

这对我有用:如果您希望通知在 android 中显示为提示通知,请修改您的消息正文以包含您的频道 ID,如下所示:

body: JSON.stringify({
        'to' : 'token',
        'notification' : {
            'title' : ' ' + this.currentUser.email + ' send you a message !',      
            'body' : text
        },
        'data': {
            'senderName' : this.currentUser.email,
            'senderUid': this.currentUser.uid 
        },
        'android': {
            'priority': 'high',
            'notification': {
                'channel_id': 'channel_id_foreground',
            },
        }
    })

推荐阅读