react native firebase文档 - 安装和配置
生命周期流:
- 注册设备以接收来自 FCM 的消息。客户端应用的实例注册以接收消息,并获取唯一标识应用实例的注册令牌。
- 发送和接收下行消息。
发送消息。应用服务器向客户端应用发送消息:
- 消息会在通知编辑器或受信任的环境中编写,并且消息请求会被发送到 FCM后端。
- FCM 后端接收消息请求,生成消息 ID 和其他元数据,并将其发送到平台特定的传输层。
- 当设备在线时,系统会通过平台特定的传输层将消息发送到设备。
- 在设备上,客户端应用会接收到消息或通知。
Firebase侦听器
https://rnfirebase.io/reference/messaging
当应用程序从退出状态打开时,按下来自FCM的通知
messaging().getInitialNotification().then((remoteMessage) => { } )
当收到任何 FCM 有效负载时(前台)
messaging().onMessage( (remoteMessage)=>{ } )
当用户按下通过 FCM 显示的通知时,如果应用程序从后台状态打开,将调用此侦听器。
messaging().onNotificationOpenedApp((remoteMessage) => { } )
当打开或接收到任何通知时,调用react-native-push-notification的回调onNotification,它传递一个带有通知数据的对象。
https://github.com/zo0r/react-native-push-notification
通知
https://rnfirebase.io/messaging/usage#notifications
应用在前台时不会显示通知,可以在onMessage里生成本地通知
PushNotification.localNotification({
channelId: 'Android',
id: id,
title: title,
message: message,
userInfo: userInfo || {},
playSound: false,
soundName: 'default',
color: color,
imageUrl: imageUrl,
smallIcon: smallIcon
});
*注意会出现问题: 通知出现时马上打开应用(或点该条推送打开应用),会生成本地通知导致重复
解决: 点击推送的时候缓存该条推送信息,onMessage的时候对比收到的数据是否是刚刚打开的那条,还有对比是否是通知列表中最新的一条
应用程序徽章
react-native-push-notification提供了getApplicationIconBadgeNumber和setApplicationIconBadgeNumber方法
push-notification-ios用到的criticalAlertSetting要ios 12.0+,在ios 12以下的系统上打开会黑屏