React Native Firebase的通知模块支持远程(FCM)和本地通知。
Firebase云消息传递(FCM)允许您的应用程序远程显示通知。为了使事情变得简单易懂,我们将React Native Firebase功能明确划分为仅限数据和通知消息。
远程通知:
React Native Firebase通知模块处理仅通知和通知+数据FCM远程消息。
有关仅限数据的FCM消息,请参阅消息传递模块。
远程通知的行为如下:
应用程序在前台 | 应用程序在后台 | 应用关闭 | |
---|---|---|---|
Android的 | onNotification 触发 | onNotificationOpened 如果点击通知则触发 | getInitialNotification 如果点击通知并打开应用程序,则会填充 |
iOS版 | onNotification 触发 | onNotificationDisplayed 如果content_available 设置为true onNotificationOpened 触发通知,则触发 | getInitialNotification 如果点击通知并打开应用程序,则会填充 |
笔记 | 没有向用户显示可见通知,您可以手动显示通知 | 该通知由移动设备的OS呈现给用户 | 该通知由移动设备的OS呈现给用户 |
Android和IOS都支持在本地触发应用程序通知的功能。这些可以立即显示,也可以安排在以后显示。
通知模块处理所有本地通知。
计划的通知行为如下:
应用程序在前台 | 应用程序在后台 | 应用关闭 | |
---|---|---|---|
Android的 | onNotification 触发 | onNotificationOpened 如果点击通知则触发 | getInitialNotification 如果点击通知并打开应用程序,则会填充 |
iOS版 | onNotification 触发 | onNotificationOpened 如果点击通知则触发 | getInitialNotification 如果点击通知并打开应用程序,则会填充 |
笔记 | 没有向用户显示可见通知,您可以手动显示通知 | 该通知由移动设备的OS呈现给用户 | 该通知由移动设备的OS呈现给用户 |
添加RNFirebaseNotificationsPackage
到您的android/app/src/main/java/com/[app name]/MainApplication.java
:
// ...
import io.invertase.firebase.RNFirebasePackage;
import io.invertase.firebase.notifications.RNFirebaseNotificationsPackage; // <-- Add this line
public class MainApplication extends Application implements ReactApplication {
// ...
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RNFirebasePackage(),
new RNFirebaseNotificationsPackage() // <-- Add this line
);
}
};
// ...
}
将以下内容添加到android/app/src/main/AndroidManifest.xml
:
添加权限:
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
在活动道具中设置应用启动模式:
<activity
...
android:launchMode="singleTop"
>
在应用程序组件中,添加元数据元素以设置默认通知图标和颜色。只要传入的消息没有明确设置图标或颜色,Android就会使用这些值。
<application ...>
<!-- Set custom default icon. This is used when no icon is set for incoming notification messages.
See README(https://goo.gl/l4GJaQ) for more. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_stat_ic_notification" />
<!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
notification message. See README(https://goo.gl/6BKBk7) for more. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/colorAccent" />
</application>
从Android 8.0(API级别26)及更高版本,支持并建议使用通知渠道。FCM提供具有基本设置的默认通知通道。如果您更喜欢创建和使用自己的默认频道,请将default_notification_channel_id设置为通知频道对象的ID,如图所示; 只要传入消息未明确设置通知通道,FCM就会使用此值。
<application ...>
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/default_notification_channel_id"/>
</application>
如果您想安排本地通知,那么您还需要将以下内容添加到以下应用程序组件中android/app/src/main/AndroidManifest.xml
:
<application ...>
<receiver android:name="io.invertase.firebase.notifications.RNFirebaseNotificationReceiver"/>
<receiver android:enabled="true" android:exported="true" android:name="io.invertase.firebase.notifications.RNFirebaseNotificationsRebootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
</application>
在您能够发送和接收通知之前,您需要确保用户已授予正确的权限:
const enabled = await firebase.messaging().hasPermission();
if (enabled) {
// user has permissions
} else {
// user doesn't have permission
}
如果用户尚未授予权限,则可以提示他们执行此操作,如下所示:
try {
await firebase.messaging().requestPermission();
// User has authorised
} catch (error) {
// User has rejected permissions
}
通知包含三种不同类型:
有关纯数据FCM消息,请参阅消息模块。
根据应用程序的状态,通知将触发两个侦听器中的一个:
onNotificationDisplayed
- 在显示特定通知时触发onNotification
- 在收到特定通知时触发// Optional: Flow type
import type { Notification } from 'react-native-firebase';
componentDidMount() {
this.notificationDisplayedListener = firebase.notifications().onNotificationDisplayed((notification: Notification) => {
// Process your notification as required
// ANDROID: Remote notifications do not contain the channel ID. You will have to specify this manually if you'd like to re-display the notification.
});
this.notificationListener = firebase.notifications().onNotification((notification: Notification) => {
// Process your notification as required
});
}
componentWillUnmount() {
this.notificationDisplayedListener();
this.notificationListener();
}
在Android上,很遗憾,无法访问已打开的远程通知的标题和正文。如果需要,您可以使用data
远程通知的部分提供此信息。
如果您的应用位于前台或后台,则可以按以下方式监听点击/点击/打开通知的时间:
// Optional: Flow type
import type { Notification, NotificationOpen } from 'react-native-firebase';
componentDidMount() {
this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen: NotificationOpen) => {
// Get the action triggered by the notification being opened
const action = notificationOpen.action;
// Get information about the notification that was opened
const notification: Notification = notificationOpen.notification;
});
}
componentWillUnmount() {
this.notificationOpenedListener();
}
如果您的应用已关闭,您可以通过点击/点按/打开通知来检查它是否已打开,如下所示:
// Optional: Flow type
import type { Notification, NotificationOpen } from 'react-native-firebase';
async componentDidMount() {
const notificationOpen: NotificationOpen = await firebase.notifications().getInitialNotification();
if (notificationOpen) {
// App was opened by a notification
// Get the action triggered by the notification being opened
const action = notificationOpen.action;
// Get information about the notification that was opened
const notification: Notification = notificationOpen.notification;
}
}
Android和iOS都允许将通知安排在将来某个时间显示。
要建立通知,请按照显示通知指南。
之前,你可以安排在Android的通知,你必须确保你已经创建了一个通知信道,如解释在这里。
// Build notification
const notification = new firebase.notifications.Notification()...;
// Schedule the notification for 1 minute in the future
const date = new Date();
date.setMinutes(date.getMinutes() + 1);
firebase.notifications().scheduleNotification(notification, {
fireDate: date.getTime(),
})
有关完整的参考文档,请参阅通知#scheduleNotification。
从Android 8.0(API级别26)开始,通知必须指定通知通道,否则它们将不会出现。
要允许React Native Firebase在所有版本的Android中无缝工作,您需要先创建一个频道,然后才能显示通知。这段代码可以重复运行多次,因此每次应用程序启动时都可以安全地运行。
// Build a channel
const channel = new firebase.notifications.Android.Channel('test-channel', 'Test Channel', firebase.notifications.Android.Importance.Max)
.setDescription('My apps test channel');
// Create the channel
firebase.notifications().android.createChannel(channel);
有关完整的参考文档,请参阅AndroidChannel和AndroidNotifications。
React Native Firebase还支持通知通道组的概念。
// Build a channel group
const channelGroup = new firebase.notifications.Android.ChannelGroup('test-group', 'Test Channel Group');
// Create the channel group
firebase.notifications().android.createChannelGroup(channelGroup);
有关完整的参考文档,请参阅AndroidChannelGroup和AndroidNotifications。
Tips:
记得导包:
import firebase from 'react-native-firebase'; import type {Notification, NotificationOpen, RemoteMessage} from 'react-native-firebase';
发送通知有两种方式:根据包名和设备的令牌。
获取令牌方法:
/** * 获取令牌 * @returns {Promise<void>} */ async msg() { const fcmToken = await firebase.messaging().getToken(); if (fcmToken) { console.log(`令牌为:${fcmToken}`) } else { // user doesn't have a device token yet alert('user doesn\'t have a device token yet') } }
接收通知的监听:
应用在前台:
this.notificationDisplayedListener = firebase.notifications().onNotificationDisplayed((notification: Notification) => { // Process your notification as required // ANDROID: Remote notifications do not contain the channel ID. You will have to specify this manually if you'd like to re-display the notification. console.log(notification); alert('onNotificationDisplayed') }); this.notificationListener = firebase.notifications().onNotification((notification: Notification) => { // Process your notification as required console.log(notification); alert('onNotification') });
notification._title
notification._body
notification._data
notification为接收到通知时拿到的对象。_title,_body等是高级选项中填写的内容
其实有两种方法接收到通知的监听,onNotificationDisplayed和onNotification,但一般通知好像
后台发的是走的onNotification,app内部发的通知走的是onNotificationDisplayed
应用在后台:
async checkNoti() { const notificationOpen: NotificationOpen = await firebase.notifications().getInitialNotification(); if (notificationOpen) { // App was opened by a notification // Get the action triggered by the notification being opened const action = notificationOpen.action; console.log(action); // Get information about the notification that was opened const notification: Notification = notificationOpen.notification; console.log(notification); } }