react-native集成FCM的消息推送功能

前提背景:
用于海外的推送消息開發(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文件的修改不要按照這個文檔,其他步驟需要做的。

image.png

截圖上千萬不能照做!
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',
      },
    },
  });
}
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,345評論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,494評論 3 416
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,283評論 0 374
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,953評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,714評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,186評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,255評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,410評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,940評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,776評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,976評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,518評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,210評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,642評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,878評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,654評論 3 391
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,958評論 2 373

推薦閱讀更多精彩內容