前提背景:
用于海外的推送消息開發(fā),一開始是集成firebase原生庫,android是沒問題的,但是ios cocospod添加FireBase第三方庫,一直編譯報錯,與Flipper庫包沖突。所以放棄這個方式,改成集成RN的@react-native-firebase/app和@react-native-firebase/messaging的庫。
官方文檔:https://rnfirebase.io/
1、用yarn 添加這兩個庫:
yarn add @react-native-firebase/app
yarn add @react-native-firebase/messaging
android配置按照這個文檔 https://rnfirebase.io/。
ios的配置除了pod文件的修改不要按照這個文檔,其他步驟需要做的。
截圖上千萬不能照做!
ios的pod添加的替代代碼如下:
#pod文件的頂部添加
RNFirebaseAsStaticFramework = true
# Override Firebase SDK Version
$FirebaseSDKVersion = '10.22.0'
#target里面添加
pod 'FirebaseCore', :modular_headers => true
pod 'FirebaseCoreInternal', :modular_headers => true
pod 'GoogleUtilities', :modular_headers => true
以上是需要添加的原生代碼的步驟
2、在react-native的項目的根目錄創(chuàng)建firebase.json文件,代碼如下:
{
"react-native": {
"android_task_executor_maximum_pool_size": 10,
"android_task_executor_keep_alive_seconds": 3,
"messaging_ios_auto_register_for_remote_messages": true
// "crashlytics_debug_enabled": true,
// "crashlytics_disable_auto_disabler": true,
// "crashlytics_auto_collection_enabled": true,
// "crashlytics_is_error_generation_on_js_crash_enabled": true,
// "crashlytics_javascript_exception_handler_chaining_enabled": true
}
}
3、獲取token、接收前后臺消息
/**
* 獲取firebase的token
*/
export function getFireBaseToken() {
messaging().getToken().then(token => {
console.log("===== getFireBaseToken token =====", token)
}).catch(error => {
console.log("===== getFireBaseToken error =====", error)
});
messaging().onTokenRefresh(token => {
console.log("===== onTokenRefresh token =====", token)
});
}
/**
* 監(jiān)聽通知消息
*/
export function getFireBaseMessage() {
if (!subscribeOnMessage) {
subscribeOnMessage = messaging().onMessage(async remoteMessage => {
console.log('==== A new FCM message arrived! ====', JSON.stringify(remoteMessage))
//ios: {"messageId":"1710141274326336","from":"369009713610","data":{},"sentTime":"1710141189","mutableContent":true,"notification":{"body":"通知文字是3月11日 15:00","title":"標題是3月11日 15:00"}}
//android: '{"notification":{"android":{},"body":"通知文字是3月11日 15:00","title":"標題是3月11日 15:00"},"sentTime":1710141244035,"data":{},"from":"369009713610","messageId":"0:1710141303098717%0a8128d30a8128d3","ttl":604800,"collapseKey":"com.booming.booming"}'
checkMessagePermission(() => {
onDisplayNotification(remoteMessage);
});
});
}
//注冊后臺的監(jiān)聽消息事件
registerBackgroundMessage();
return subscribeOnMessage;
}
/**
* 監(jiān)聽后臺的通知消息(不能放在index.js,需要等待 第三方庫類初始化)
* !!!如果存在具有此notification屬性的傳入消息,并且應用程序當前不可見(退出或在后臺),則會在設備上顯示通知。但是,如果應用程序位于前臺,則將傳遞包含通知數(shù)據(jù)的事件,并且不會顯示可見的通知。
*/
export function registerBackgroundMessage() {
console.log("======== registerBackgroundMessage =======")
messaging().setBackgroundMessageHandler(async (remoteMessage) => {
console.log('==== Message handled in the background! ====', remoteMessage);
// 如果存在具有此notification屬性的傳入消息,系統(tǒng)會彈出來通知,最好統(tǒng)一由notifee處理
// checkMessagePermission(() => {
// onDisplayNotification(remoteMessage);
// });
})
}
4、通知權限的詢問 ,使用了第三方庫react-native-permissions
/**
* 獲取設備的app是否打開了通知權限
*/
export async function checkMessagePermission(callback, failCallback) {
checkNotifications().then(async ({ status }) => {
console.log("====== checkNotifications ===", status)
if (status == 'granted') {//android權限即使是同意了,使用PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS)方法,返回的是:never_ask_again
//Android或ios已經(jīng)有通知的權限
callback && callback();
} else {
if (Platform.OS == 'ios') {//讓ios的設置頁面顯示“通知”的菜單,并請求該權限
const authorizationStatus = await messaging().requestPermission();//首次詢問才有權限申請彈窗
console.log('===== ios Permission status:', authorizationStatus);
if (authorizationStatus) {
//ios 已經(jīng)有權限
callback && callback();
} else {
// openSettings();
failCallback && failCallback();
}
} else if (Platform.OS == "android") {//首次詢問才有權限申請彈窗
const result = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS);
console.log("======== android Permission status:", result);
if (result == 'granted') {
//android 已經(jīng)有權限
callback && callback();
} else {
// openSettings();
failCallback && failCallback();
}
}
}
}).catch(err => {
console.log("====== checkNotifications error===", err)
})
}
5、顯示通知,我使用了@notifee/react-native庫
messaging().onMessage()是App前臺接收消息的事件(前臺是指app頁面在當前屏幕上顯示,后臺是指App進程殺掉,app應用退到后臺,當前屏幕看不到app頁面)
onMessage接收到的消息需要手動顯示通知,如下:
/**
* @param {*} remoteMessage
* 顯示消息通知
*/
export async function onDisplayNotification(remoteMessage) {
// const settings = await notifee.requestPermission();// Request permissions (required for iOS)
const { notification, data } = remoteMessage;
// Create a channel (required for Android)
const channelId = await notifee.createChannel({
id: 'default',
name: 'Default Channel',
// badge: true,
// vibration: true,
// vibrationPattern: [300, 500],
// importance: AndroidImportance.HIGH,
});
// Display a notification
await notifee.displayNotification({
title: notification.title,
body: notification.body,
data: data,
android: {
channelId,
largeIcon: 'ic_launcher',
smallIcon: 'ic_notification', // defaults to 'ic_launcher'. 安卓5后 不允許在通知欄使用彩色圖標
// pressAction is needed if you want the notification to open the app when pressed
pressAction: {
id: 'default',
},
},
});
}
messaging().setBackgroundMessageHandler()是后臺接受消息的事件,firebase會自動顯示該通知,不需要再手動彈出通知。
(官方文檔寫:如果存在具有此notification屬性的傳入消息,并且應用程序當前不可見(退出或在后臺),則會在設備上顯示通知。但是,如果應用程序位于前臺,則將傳遞包含通知數(shù)據(jù)的事件,并且不會顯示可見的通知。)
5、處理點擊的通知消息,注冊notifee的前后臺事件
/**
* 通知前臺的點擊監(jiān)聽事件
*/
export function notifeeForegroundEvent() {
try {
if (!subscribeNotifeeFore) {
//點擊通知的事件
subscribeNotifeeFore = notifee.onForegroundEvent(({ type, detail }) => {
console.log("==== onForegroundEvent =====type:" + type, detail)
//{"notification": {"body": "通知文字是3月12日 12:00", "data": {"id": "271", "pageName": "MerchantTaskDetailPage"}, "id": "5fdeT8yJgHvCiVnAJQGf"}
switch (type) {
case EventType.DISMISSED:
console.log('User dismissed notification', detail.notification);
break;
case EventType.PRESS:
console.log('User pressed notification', detail.notification);
processNotification(detail.notification);
break;
}
});
}
} catch (error) {
console.log("===== notifeeForegroundEvent error ->", error);
}
return subscribeNotifeeFore;
}
/**
* 通知后臺的點擊事件(不能放在index.js,需要等待 第三方庫類初始化)
*/
export function notifeeBackgroundEvent() {
console.log("====== notifeeBackgroundEvent init =======")
try {
notifee.onBackgroundEvent(async ({ type, detail }) => {
const { notification } = detail;
console.log("====== notifeeBackgroundEvent =====type:" + type, detail);
// Check if the user pressed the "Mark as read" action
// if (type === EventType.ACTION_PRESS) {// && pressAction.id === 'mark-as-read'
// Remove the notification
// await notifee.cancelNotification(notification.id);
// }
switch (type) {
case EventType.DISMISSED:
console.log('User dismissed notification', detail.notification);
break;
case EventType.PRESS:
console.log('User pressed notification', detail.notification);
// if (Platform.OS == 'ios') {//Android的后臺消息處理在 messaging().getInitialNotification()方法調用后
// processNotification(detail.notification);
// }
await notifee.decrementBadgeCount();
await notifee.cancelNotification(notification.id);
break;
}
});
} catch (error) {
console.log("===== notifeeBackgroundEvent error ->", error);
}
}
注意,根據(jù)app應用的前后臺的狀態(tài)不一樣,事件處理也不同的。
(1)、app進程殺掉,點擊通知,
iOS會轉為notifeeForegroundEvent事件;
android的messaging().getInitialNotification()和messaging().onNotificationOpenedApp的方法來獲取該通知數(shù)據(jù)
(2)、app在后臺,點擊通知,
iOS會轉為notifeeForegroundEvent事件;
android走notifeeBackgroundEvent事件;
(3)、app在前臺,ios和android走notifeeForegroundEvent事件
6、部分方法需要放在index.js里面執(zhí)行,
import "react-native-gesture-handler";
import { AppRegistry } from "react-native";
import App from "./App";
import { name as appName } from "./app.json";
import { notifeeBackgroundEvent, registerBackgroundMessage } from "./src/business/FirebaseMessageBusiness";
//在FirebaseMessageBusiness會再次調用,防止事件注冊不上
registerBackgroundMessage();
notifeeBackgroundEvent();
AppRegistry.registerComponent(appName, () => App);
FirebaseMessageBusiness 文件的完整代碼如下:
import messaging from '@react-native-firebase/messaging';
import { PermissionsAndroid, Platform } from 'react-native';
import { checkNotifications, openSettings } from 'react-native-permissions';
import notifee, { EventType } from '@notifee/react-native';
import { NavigationService } from '../utils/All';
import appModel from '../model/AppModel';
let subscribeOnMessage = null;//消息監(jiān)聽事件
let subscribeNotifeeFore = null;//通知點擊監(jiān)聽事件
let subscribeOnNotifyOpened = null;
//初始化
export async function initFireBaseMessage() {
try {
if (Platform.OS == 'android') {//ios的后臺消息都會轉為notifeeForegroundEvent事件去接收
//getInitialNotification: When the application is opened from a quit state.
const remotMessage = await messaging().getInitialNotification();
console.log("======= android remotMessage =====" + JSON.stringify(remotMessage));
if (remotMessage) {
processNotification(remotMessage);
}
if (!subscribeOnNotifyOpened) {
// onNotificationOpenedApp: When the application is running, but in the background.由系統(tǒng)彈出來的通知消息,點擊該通知會觸發(fā)這個方法
//(場景一般是android應用在后臺的時候,有message觸發(fā)setBackgroundMessageHandler方法,系統(tǒng)會彈出來通知)
subscribeOnNotifyOpened = messaging().onNotificationOpenedApp((message) => {
console.log("=======android onNotificationOpenedApp =====" + JSON.stringify(message));
if (message) {
processNotification(message);
}
});
}
}
} catch (error) {
console.log("====== initFireBaseMessage ===", error)
}
getFireBaseToken();
getFireBaseMessage();
notifeeForegroundEvent();
//注冊通知的后臺事件,https://notifee.app/react-native/docs/events
notifeeBackgroundEvent();
checkMessagePermission(() => {
console.log("==== initFireBaseMessage checkMessagePermission ====")
});
}
//移除所有的事件
export function removeMsgSubscribe() {
if (subscribeOnMessage) {
subscribeOnMessage();
}
if (subscribeNotifeeFore) {
subscribeNotifeeFore();
}
if (subscribeOnNotifyOpened) {
subscribeOnNotifyOpened();
}
}
/**
* 獲取firebase的token
*/
export function getFireBaseToken() {
messaging().getToken().then(token => {
console.log("===== getFireBaseToken token =====", token)
}).catch(error => {
console.log("===== getFireBaseToken error =====", error)
});
messaging().onTokenRefresh(token => {
console.log("===== onTokenRefresh token =====", token)
});
}
/**
* 監(jiān)聽通知消息
*/
export function getFireBaseMessage() {
if (!subscribeOnMessage) {
subscribeOnMessage = messaging().onMessage(async remoteMessage => {
console.log('==== A new FCM message arrived! ====', JSON.stringify(remoteMessage))
//ios: {"messageId":"1710141274326336","from":"369009713610","data":{},"sentTime":"1710141189","mutableContent":true,"notification":{"body":"通知文字是3月11日 15:00","title":"標題是3月11日 15:00"}}
//android: '{"notification":{"android":{},"body":"通知文字是3月11日 15:00","title":"標題是3月11日 15:00"},"sentTime":1710141244035,"data":{},"from":"369009713610","messageId":"0:1710141303098717%0a8128d30a8128d3","ttl":604800,"collapseKey":"com.booming.booming"}'
checkMessagePermission(() => {
onDisplayNotification(remoteMessage);
});
});
}
//注冊后臺的監(jiān)聽消息事件
registerBackgroundMessage();
return subscribeOnMessage;
}
/**
* 監(jiān)聽后臺的通知消息(不能放在index.js,需要等待 第三方庫類初始化)
* !!!如果存在具有此notification屬性的傳入消息,并且應用程序當前不可見(退出或在后臺),則會在設備上顯示通知。但是,如果應用程序位于前臺,則將傳遞包含通知數(shù)據(jù)的事件,并且不會顯示可見的通知。
*/
export function registerBackgroundMessage() {
console.log("======== registerBackgroundMessage =======")
messaging().setBackgroundMessageHandler(async (remoteMessage) => {
console.log('==== Message handled in the background! ====', remoteMessage);
// 如果存在具有此notification屬性的傳入消息,系統(tǒng)會彈出來通知,最好統(tǒng)一由notifee處理
// checkMessagePermission(() => {
// onDisplayNotification(remoteMessage);
// });
})
}
/**
* 獲取設備的app是否打開了通知權限
*/
export async function checkMessagePermission(callback, failCallback) {
checkNotifications().then(async ({ status }) => {
console.log("====== checkNotifications ===", status)
if (status == 'granted') {//android權限即使是同意了,使用PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS)方法,返回的是:never_ask_again
//Android或ios已經(jīng)有通知的權限
callback && callback();
} else {
if (Platform.OS == 'ios') {//讓ios的設置頁面顯示“通知”的菜單,并請求該權限
const authorizationStatus = await messaging().requestPermission();//首次詢問才有權限申請彈窗
console.log('===== ios Permission status:', authorizationStatus);
if (authorizationStatus) {
//ios 已經(jīng)有權限
callback && callback();
} else {
// openSettings();
failCallback && failCallback();
}
} else if (Platform.OS == "android") {//首次詢問才有權限申請彈窗
const result = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS);
console.log("======== android Permission status:", result);
if (result == 'granted') {
//android 已經(jīng)有權限
callback && callback();
} else {
// openSettings();
failCallback && failCallback();
}
}
}
}).catch(err => {
console.log("====== checkNotifications error===", err)
})
}
/**
* 通知前臺的點擊監(jiān)聽事件
*/
export function notifeeForegroundEvent() {
try {
if (!subscribeNotifeeFore) {
//點擊通知的事件
subscribeNotifeeFore = notifee.onForegroundEvent(({ type, detail }) => {
console.log("==== onForegroundEvent =====type:" + type, detail)
//{"notification": {"body": "通知文字是3月12日 12:00", "data": {"id": "271", "pageName": "MerchantTaskDetailPage"}, "id": "5fdeT8yJgHvCiVnAJQGf"}
switch (type) {
case EventType.DISMISSED:
console.log('User dismissed notification', detail.notification);
break;
case EventType.PRESS:
console.log('User pressed notification', detail.notification);
processNotification(detail.notification);
break;
}
});
}
} catch (error) {
console.log("===== notifeeForegroundEvent error ->", error);
}
return subscribeNotifeeFore;
}
/**
* 通知后臺的點擊事件(不能放在index.js,需要等待 第三方庫類初始化)
*/
export function notifeeBackgroundEvent() {
console.log("====== notifeeBackgroundEvent init =======")
try {
notifee.onBackgroundEvent(async ({ type, detail }) => {
const { notification } = detail;
console.log("====== notifeeBackgroundEvent =====type:" + type, detail);
// Check if the user pressed the "Mark as read" action
// if (type === EventType.ACTION_PRESS) {// && pressAction.id === 'mark-as-read'
// Remove the notification
// await notifee.cancelNotification(notification.id);
// }
switch (type) {
case EventType.DISMISSED:
console.log('User dismissed notification', detail.notification);
break;
case EventType.PRESS:
console.log('User pressed notification', detail.notification);
// if (Platform.OS == 'ios') {//Android的后臺消息處理在 messaging().getInitialNotification()方法調用后
// processNotification(detail.notification);
// }
await notifee.decrementBadgeCount();
await notifee.cancelNotification(notification.id);
break;
}
});
} catch (error) {
console.log("===== notifeeBackgroundEvent error ->", error);
}
}
/**
* 處理消息
*/
export function processNotification(notification) {
try {
const dataObj = notification.data;
console.log("====== dataObj ===notification:", JSON.stringify(notification), dataObj)
console.log('appModel.isShowSplash: ', appModel.isShowSplash);
if (appModel.isShowSplash) {
NavigationService.navigate(dataObj.pageName, { ...dataObj });
} else {
appModel.setNoticeInfo(dataObj)
}
} catch (error) {
console.log("==== processNotification error!", error)
}
}
/**
* @param {*} remoteMessage
* 顯示消息通知
*/
export async function onDisplayNotification(remoteMessage) {
// const settings = await notifee.requestPermission();// Request permissions (required for iOS)
const { notification, data } = remoteMessage;
// Create a channel (required for Android)
const channelId = await notifee.createChannel({
id: 'default',
name: 'Default Channel',
// badge: true,
// vibration: true,
// vibrationPattern: [300, 500],
// importance: AndroidImportance.HIGH,
});
// Display a notification
await notifee.displayNotification({
title: notification.title,
body: notification.body,
data: data,
android: {
channelId,
largeIcon: 'ic_launcher',
smallIcon: 'ic_notification', // defaults to 'ic_launcher'. 安卓5后 不允許在通知欄使用彩色圖標
// pressAction is needed if you want the notification to open the app when pressed
pressAction: {
id: 'default',
},
},
});
}