您不需要其他答案中建议的其他软件包。
使用 RNFirebase.io,你可以轻松搞定。
如果您在应用程序处于后台时收到通知,您必须自己处理才能显示此通知。例如,请参阅我的 init-Method for Push-Notifications。
import firebase from 'react-native-firebase';
const notifications = firebase.notifications();
....
notifications.onNotification((notif) => {
notif.android.setChannelId('app-infos');
notifications.displayNotification(notif);
});
您可以使用displayNotification 进行操作。但请确保在调用它之前设置通知通道,否则它无法在 >= Android 8.0 上运行
顺便说一句:确保您完全设置 Firebase 并授予所有必要的权限,以便在应用关闭或在后台时能够监听通知。 (https://rnfirebase.io/docs/v5.x.x/notifications/android)
附录
我添加这个作为示例来展示我如何将 firebase-notification-stuff 实现为一个小型库(如果您不需要它,请删除 redux-stuff):
import firebase from 'react-native-firebase';
import { saveNotificationToken } from 'app/actions/firebase';
import reduxStore from './reduxStore';
import NavigationService from './NavigationService';
const messaging = firebase.messaging();
const notifications = firebase.notifications();
const crashlytics = firebase.crashlytics();
function registerNotifChannels() {
try {
// Notification-Channels is a must-have for Android >= 8
const channel = new firebase.notifications.Android.Channel(
'app-infos',
'App Infos',
firebase.notifications.Android.Importance.Max,
).setDescription('General Information');
notifications.android.createChannel(channel);
} catch (error) {
crashlytics.log(`Error while creating notification-channel \n ${error}`);
}
}
// This is the Promise object that we use to initialise the push
// notifications. It will resolve when the token was successfully retrieved. The
// token is returned as the value of the Promise.
const initPushNotifs = new Promise(async (resolve, reject) => {
try {
const isPermitted = await messaging.hasPermission();
if (isPermitted) {
registerNotifChannels();
try {
const token = await messaging.getToken();
if (token) {
resolve(token);
}
} catch (error) {
crashlytics.log(`Error: failed to get notification-token \n ${error}`);
}
}
} catch (error) {
crashlytics.log(`Error while checking notification-permission\n ${error}`);
}
// If we get this far then there was no token available (or something went
// wrong trying to get it)
reject();
});
function init() {
// Initialise the push notifications, then save the token when/if it's available
initPushNotifs.then(token => reduxStore.dispatch(saveNotificationToken(token)));
// Save the (new) token whenever it changes
messaging.onTokenRefresh(token => reduxStore.dispatch(saveNotificationToken(token)));
notifications.onNotification((notif) => {
notif.android.setChannelId('app-infos');
notifications.displayNotification(notif);
});
notifications.onNotificationOpened((notif) => {
const { notification: { _data: { chatroom: chatRoomId } } = {} } = notif;
if (chatRoomId) {
NavigationService.navigate('ChatRoom', { chatRoomId });
}
});
}
export default {
init,
};
有了这个,只需转到您的 index.js 文件(或您的应用程序的根文件,无论它如何命名)并调用 init-Metod:
...
import LPFirebase from 'lib/LPFirebase';
LPFirebase.init();