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

React Native Firebase通知在应用前台不显示,如何强制推送?

解决React Native Firebase前台无法接收通知的问题

Firebase Cloud Messaging(FCM)在应用前台运行时,不会自动弹出系统通知,需要手动处理消息并创建本地通知。以下是实现全状态通知接收的具体步骤:

核心逻辑

FCM针对应用不同状态的消息处理规则:

  • 后台/关闭状态:系统自动接管并展示通知
  • 前台状态:消息仅传递到onMessage回调,需手动触发本地通知

具体实现

1. 监听前台消息并创建本地通知

使用@react-native-firebase/messaging监听前台消息,配合@react-native-firebase/notifications生成系统通知:

import React, { useEffect } from 'react';
import messaging from '@react-native-firebase/messaging';
import notifications from '@react-native-firebase/notifications';

function App() {
  useEffect(() => {
    // 监听前台FCM消息
    const unsubscribe = messaging().onMessage(async remoteMessage => {
      // 初始化Android通知渠道(8.0+ 必填)
      const channelId = await initNotificationChannel();
      
      // 弹出本地通知
      await notifications().displayNotification({
        title: remoteMessage.notification?.title || '新通知',
        body: remoteMessage.notification?.body || '您有一条新消息',
        channelId: channelId,
        data: remoteMessage.data, // 携带自定义业务数据
      });
    });

    // 组件卸载时取消监听
    return unsubscribe;
  }, []);

  return <>{/* 你的应用内容 */}</>;
}

// Android创建通知渠道
async function initNotificationChannel() {
  const channelId = 'default_notify_channel';
  const channel = new notifications.NotificationChannel(
    channelId,
    '默认通知渠道',
    notifications.AndroidImportance.HIGH
  ).setDescription('接收应用所有通知');

  await notifications().android.createChannel(channel);
  return channelId;
}

export default App;

2. iOS 额外配置

  • 在Info.plist中添加后台模式与代理配置:
<key>UIBackgroundModes</key>
<array>
  <string>remote-notification</string>
</array>
<key>FirebaseAppDelegateProxyEnabled</key>
<false/>
  • 确保请求包含alert权限的通知授权:
async function requestNotifyPermission() {
  const authStatus = await messaging().requestPermission({
    alert: true,
    badge: true,
    sound: true,
  });
  const isAuthorized = authStatus === messaging.AuthorizationStatus.AUTHORIZED || 
                       authStatus === messaging.AuthorizationStatus.PROVISIONAL;
  if (!isAuthorized) {
    console.log('用户未授权通知权限');
  }
}

3. 验证要点

  • 确认@react-native-firebase/messaging和@react-native-firebase/notifications已正确安装链接
  • 测试时保持应用前台运行,通过FCM控制台发送通知,检查是否正常弹出

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 09:35:36