我正在使用我的 React native 应用程序向使用 Firebase 云消息传递的 Android 用户设置推送通知。到目前为止,我主要关注了这个tutorial .我设法使推送通知显示在锁定屏幕上,并在应用程序处于前台时处理它们。但是,当应用程序在后台运行时,我无法将通知显示为弹出窗口。它出现在通知托盘上,但不会像 gmail 或 whatsapp 的通知那样显示弹出窗口。
我认为我的问题是我没有随消息发送正确的参数。我正在使用 firebase 控制台,所以它不是很灵活。我如何配置(以编程方式)通知在收到时显示为弹出窗口?
编辑:
设置通知 channel 适用于较新的 Android 设备 - 在 Android 8.1(API 级别 27)上测试。
在旧设备上 - 在 Android 6.0(API 级别 23)上进行测试 - 提示通知仍然不会出现。我正在使用 aws sns 控制台发送以下消息:
{
priority: 'high',
content_available: true,
notification: {
title: 'hello',
body: 'Just test',
android_channel_id: 'test-channel',
sound: 'default'
},
data: { title: 'title', body: 'body', sound: 'default' }
}
我还使用 Firebase 控制台设置 Priority High 和 Sound Enabled 发送消息,使用和不使用 Android Channel Id。这些都没有用。通知静静地到达托盘栏。这discussion显示相同的问题,但 solution一个人指出对我没有用。我没有经常编辑 react-native 库代码。我尝试了旧版 Android 版本(前景)的问题部分,它让抬头出现在前景上,但不出现在背景上,这是这里的预期行为。
此外,对于使用此 React native 包(github issue、github issue)的许多人来说,这似乎是一个 Unresolved 问题。
所以,我想我应该重新表述我的问题。对于 Android 7.1 或更低版本(在 6.0 上测试):
设置 priority='high' 和 notification.sound='default' 是否足以显示提示通知? (根据我的研究应该是)
我是否需要对我的应用程序代码进行任何进一步的配置,以从通知静默到达托盘栏到它作为提醒出现?
最佳答案
感谢@ismailalaoui 对这个问题的贡献。当系统托盘收到通知时,我无法将通知显示为抬头,因此我不得不进行变通。我将展示我是如何使用 react-native-firebase 做到这一点的。
对于新的安卓设备,you should create a notification channel .在您的 App.js 中添加以下内容
componentDidMount(){
...
const channel = new firebase.notifications.Android.Channel('test-channel', 'Test Channel', firebase.notifications.Android.Importance.Max).setDescription('My apps test channel'); //add this line
firebase.notifications().android.createChannel(channel); //add this line
}
对于旧设备,我不得不采取变通办法。我没有使用通知消息,而是使用了数据消息,因此您可以在后台收听。 See item 4 .
首先新建一个文件bgMessaging.js:
import firebase from 'react-native-firebase';
export default async (message) => {
// handle your message
const notification = new firebase.notifications.Notification()
.setNotificationId(message.messageId)
.setTitle(message.data.title)
.setBody(message.data.body)
.android.setChannelId('test-channel')
.android.setSmallIcon('ic_launcher')
.android.setPriority(firebase.notifications.Android.Priority.Max)
.setSound('default');
await firebase.notifications().displayNotification(notification);
console.log({message})
return Promise.resolve();
}
在您的 index.js 文件中,添加:
import bgMessaging from './src/bgMessaging'; // <-- Import the file you just created
...
AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage', () => bgMessaging);
react-native-firebase 使用 Headless JS 来运行您在 bgMessaging
中定义的 javascript 代码。根据docs您需要将服务添加到 AndroidManifest.xml。
在 android/app/src/main/AndroidManifest.xml 添加:
<application>
...
<service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" /> <!--Add this-->
...
</application>
关于android - 当应用程序在后台使用 firebase 时,使推送通知显示为弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56621363/