当前位置:首页 > React

react native 推送实现

2026-01-26 21:17:18React

集成 Firebase Cloud Messaging (FCM)

安装 Firebase 依赖库并配置 Android/iOS 项目。对于 Android,需在 android/app/build.gradle 中添加 Firebase SDK 依赖。iOS 需通过 CocoaPods 安装 Firebase 并配置 GoogleService-Info.plist 文件。

yarn add @react-native-firebase/app @react-native-firebase/messaging

请求推送权限

在应用启动时请求用户通知权限(iOS 需显式调用,Android 默认授予)。使用 messaging().requestPermission() 检查权限状态,并在权限授予后获取设备 token。

import messaging from '@react-native-firebase/messaging';

async function requestUserPermission() {
  const authStatus = await messaging().requestPermission();
  const enabled = 
    authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
    authStatus === messaging.AuthorizationStatus.PROVISIONAL;
  if (enabled) {
    const token = await messaging().getToken();
    console.log('FCM Token:', token);
  }
}

处理前台和后台消息

通过 messaging().onMessage 监听前台通知,使用 setBackgroundMessageHandler 处理后台消息。需在 index.js 中注册后台处理器。

// 前台消息处理
messaging().onMessage(async remoteMessage => {
  console.log('Foreground Message:', remoteMessage);
});

// 后台消息处理(需在 index.js 中注册)
messaging().setBackgroundMessageHandler(async remoteMessage => {
  console.log('Background Message:', remoteMessage);
});

处理通知点击

使用 messaging().getInitialNotification() 获取应用关闭时点击的通知数据,通过 messaging().onNotificationOpenedApp 监听应用处于后台时的点击事件。

// 检查初始通知
messaging().getInitialNotification().then(remoteMessage => {
  if (remoteMessage) {
    console.log('Launched by notification:', remoteMessage);
  }
});

// 监听通知点击
messaging().onNotificationOpenedApp(remoteMessage => {
  console.log('Notification clicked:', remoteMessage);
});

测试推送通知

通过 Firebase 控制台或 Postman 调用 FCM API 发送测试通知。需使用设备 token 和服务器密钥(可在 Firebase 项目设置中获取)。

react native 推送实现

# 示例 cURL 命令
curl -X POST \
  -H "Authorization: key=<SERVER_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "to": "<DEVICE_TOKEN>",
    "notification": {
      "title": "Test Title",
      "body": "Test Body"
    }
  }' \
  https://fcm.googleapis.com/fcm/send

注意事项

  • Android 配置:确保 android/app/src/main/AndroidManifest.xml 包含正确的 intent-filterservice 声明。
  • iOS 证书:需在 Apple Developer 后台配置 APNs 证书并上传至 Firebase。
  • 调试:使用 adb logcat 或 Xcode 控制台查看推送日志。

标签: reactnative
分享给朋友:

相关文章

如何生成react代码

如何生成react代码

使用 Create React App 生成项目 安装 Node.js 后,通过命令行工具运行以下命令创建新项目: npx create-react-app my-app cd my-app npm…

如何react页面

如何react页面

创建 React 页面 使用 create-react-app 快速初始化项目: npx create-react-app my-app cd my-app npm start 基础页面结构 在 s…

react如何销毁

react如何销毁

React 组件销毁的机制 在 React 中,组件的销毁通常由 React 的生命周期管理。当组件从 DOM 中移除时,React 会自动触发销毁相关的生命周期方法。以下是关键点: 组件的销毁通常…

react如何卸载

react如何卸载

卸载 React 项目或依赖 如果需要完全卸载 React 项目或相关依赖,可以按照以下步骤操作: 删除项目文件夹 直接删除整个项目文件夹是最彻底的方式。确保已备份重要代码或配置文件。 卸载全局安…

react如何重置

react如何重置

重置 React 应用的状态 使用 useState 钩子重新初始化状态变量是最直接的方法。将状态变量重置为初始值或空值即可完成重置。 const [count, setCount] = useSt…

如何调试react

如何调试react

调试 React 应用的方法 使用 React Developer Tools 安装浏览器扩展(Chrome/Firefox),通过组件树查看组件状态、props 和 hooks。支持实时编辑 pro…