You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android升级compileSdkVersion至31后React Native Firebase Messaging无法收通知

解决Android SDK31升级后React Native Firebase Messaging无法接收推送的问题

当你把Android项目的compileSdkVersion和targetSdkVersion升级到31后,无法接收推送主要是因为Android 12引入了新的通知权限和渠道要求,结合你使用的@react-native-firebase/messaging": "^14.12.0"版本,按以下步骤排查修复:

  • 添加并申请POST_NOTIFICATIONS权限
    Android 12开始要求显式申请通知权限,首先在AndroidManifest.xml中添加权限声明:

    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    

    然后在RN代码中动态申请权限(使用PermissionsAndroid):

    import { PermissionsAndroid } from 'react-native';
    
    const requestNotificationPermission = async () => {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS,
        {
          title: '通知权限申请',
          message: '应用需要权限发送通知',
          buttonNeutral: '稍后询问',
          buttonNegative: '取消',
          buttonPositive: '允许',
        },
      );
      return granted === PermissionsAndroid.RESULTS.GRANTED;
    };
    
    // 在App启动时调用
    requestNotificationPermission();
    
  • 升级React Native Firebase Messaging版本
    14.12.0版本对Android 12的适配不够完善,建议升级到15.x及以上版本(该版本开始全面支持Android 12):

    npm install @react-native-firebase/messaging@^15.0.0
    # 或升级到最新稳定版
    npm install @react-native-firebase/messaging@latest
    
  • 配置通知渠道
    Android 12要求所有通知必须绑定到指定渠道,初始化时创建默认渠道:

    import messaging from '@react-native-firebase/messaging';
    
    const createNotificationChannel = async () => {
      await messaging().createChannel({
        id: 'default_channel',
        name: '默认通知渠道',
        description: '接收应用所有通知',
        sound: true,
        importance: messaging.Importance.HIGH,
      });
    };
    
    // 在App启动时调用
    createNotificationChannel();
    

    同时确保推送payload中指定channelId为你创建的渠道ID。

  • 检查后台消息服务配置
    确认你的MyFirebaseMessagingService(自定义消息服务)在AndroidManifest.xml中正确注册,并且适配Android 12的导出规则:

    <service
      android:name=".MyFirebaseMessagingService"
      android:exported="false">
      <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
      </intent-filter>
    </service>
    

    如果是处理数据消息(无notification字段的payload),需要在服务的onMessageReceived方法中手动构建并显示通知。

  • 验证推送Payload格式
    确保推送的payload包含channelId字段,示例:

    {
      "to": "你的设备Token",
      "notification": {
        "title": "测试通知",
        "body": "这是一条测试推送",
        "channelId": "default_channel"
      }
    }
    

内容的提问来源于stack exchange,提问作者mahdi souilmi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 06:30:47