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

前提背景:
用于海外的推送消息开发,一开始是集成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的项目的根目录创建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)
  });
}

/**
 * 监听通知消息
 */
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);
      });
    });
  }
  //注册后台的监听消息事件
  registerBackgroundMessage();

  return subscribeOnMessage;
}

/**
 * 监听后台的通知消息(不能放在index.js,需要等待 第三方库类初始化)
 * !!!如果存在具有此notification属性的传入消息,并且应用程序当前不可见(退出或在后台),则会在设备上显示通知。但是,如果应用程序位于前台,则将传递包含通知数据的事件,并且不会显示可见的通知。
 */
export function registerBackgroundMessage() {
  console.log("======== registerBackgroundMessage =======")
  messaging().setBackgroundMessageHandler(async (remoteMessage) => {
    console.log('==== Message handled in the background! ====', remoteMessage);
    // 如果存在具有此notification属性的传入消息,系统会弹出来通知,最好统一由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已经有通知的权限
      callback && callback();
    } else {
      if (Platform.OS == 'ios') {//让ios的设置页面显示“通知”的菜单,并请求该权限
        const authorizationStatus = await messaging().requestPermission();//首次询问才有权限申请弹窗
        console.log('===== ios Permission status:', authorizationStatus);
        if (authorizationStatus) {
          //ios 已经有权限
          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 已经有权限
          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属性的传入消息,并且应用程序当前不可见(退出或在后台),则会在设备上显示通知。但是,如果应用程序位于前台,则将传递包含通知数据的事件,并且不会显示可见的通知。)

5、处理点击的通知消息,注册notifee的前后台事件

/**
 * 通知前台的点击监听事件
 */
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);
  }

}

注意,根据app应用的前后台的状态不一样,事件处理也不同的。
(1)、app进程杀掉,点击通知,
iOS会转为notifeeForegroundEvent事件;
android的messaging().getInitialNotification()和messaging().onNotificationOpenedApp的方法来获取该通知数据
(2)、app在后台,点击通知,
iOS会转为notifeeForegroundEvent事件;
android走notifeeBackgroundEvent事件;
(3)、app在前台,ios和android走notifeeForegroundEvent事件

6、部分方法需要放在index.js里面执行,

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;//消息监听事件
let subscribeNotifeeFore = null;//通知点击监听事件
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.由系统弹出来的通知消息,点击该通知会触发这个方法
        //(场景一般是android应用在后台的时候,有message触发setBackgroundMessageHandler方法,系统会弹出来通知)
        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)
  });
}

/**
 * 监听通知消息
 */
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);
      });
    });
  }
  //注册后台的监听消息事件
  registerBackgroundMessage();

  return subscribeOnMessage;
}

/**
 * 监听后台的通知消息(不能放在index.js,需要等待 第三方库类初始化)
 * !!!如果存在具有此notification属性的传入消息,并且应用程序当前不可见(退出或在后台),则会在设备上显示通知。但是,如果应用程序位于前台,则将传递包含通知数据的事件,并且不会显示可见的通知。
 */
export function registerBackgroundMessage() {
  console.log("======== registerBackgroundMessage =======")
  messaging().setBackgroundMessageHandler(async (remoteMessage) => {
    console.log('==== Message handled in the background! ====', remoteMessage);
    // 如果存在具有此notification属性的传入消息,系统会弹出来通知,最好统一由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已经有通知的权限
      callback && callback();
    } else {
      if (Platform.OS == 'ios') {//让ios的设置页面显示“通知”的菜单,并请求该权限
        const authorizationStatus = await messaging().requestPermission();//首次询问才有权限申请弹窗
        console.log('===== ios Permission status:', authorizationStatus);
        if (authorizationStatus) {
          //ios 已经有权限
          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 已经有权限
          callback && callback();
        } else {
          // openSettings();
          failCallback && failCallback();
        }
      }

    }
  }).catch(err => {
    console.log("====== checkNotifications error===", err)
  })
}

/**
 * 通知前台的点击监听事件
 */
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',
      },
    },
  });
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,290评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,399评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,021评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,034评论 0 207
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,412评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,651评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,902评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,605评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,339评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,586评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,076评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,400评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,060评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,851评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,685评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,595评论 2 270

推荐阅读更多精彩内容