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

求助:如何使用RNFirebase在React Native后台显示Heads-Up通知

Fixing Heads-Up Notifications in Background/Closed State with React Native Firebase

Hey there, let's get those heads-up notifications working for your app when it's in the background or closed! The issue with your current setup is that your background messaging task just resolves a promise without actually creating and displaying a notification. Here's how to fix it step by step:

1. Update Your Background Messaging Handler

Your bgMessaging.js needs to explicitly create and display a heads-up notification. Right now, it's not doing anything with the incoming message. Replace it with this code:

// @flow
import firebase from 'react-native-firebase';
import type { RemoteMessage } from 'react-native-firebase';

export default async (message: RemoteMessage) => {
  // Build the notification using data from the incoming message
  const notification = new firebase.notifications.Notification()
    .setNotificationId(message.messageId)
    // Fallback to default text if the message doesn't have notification fields
    .setTitle(message.notification?.title || 'Alert')
    .setBody(message.notification?.body || 'You have a new message')
    .setSound('default') // Play default notification sound

    // Android-specific settings for heads-up
    .android.setPriority(firebase.notifications.Android.Priority.High)
    .android.setChannelId('high-priority-channel') // We'll create this channel next
    .android.setSmallIcon('ic_notification') // Replace with your app's notification icon (add this to drawables)

    // iOS-specific settings for heads-up
    .ios.setAlert(true)
    .ios.setBadge(1); // Optional: Update app badge count

  // Display the notification to the user
  await firebase.notifications().displayNotification(notification);

  return Promise.resolve();
};

2. Initialize Notification Channels (Android 8.0+)

Android requires notification channels for all notifications starting from API 26. Add this code to your main app component (e.g., App.js) to create a high-priority channel on app launch:

import firebase from 'react-native-firebase';
import { useEffect } from 'react';

function App() {
  useEffect(() => {
    // Create high-priority notification channel
    const highPriorityChannel = new firebase.notifications.Android.Channel(
      'high-priority-channel',
      'Critical Alerts',
      firebase.notifications.Android.Importance.High
    )
    .setDescription('Used for heads-up notifications that need immediate attention')
    .enableVibration(true)
    .enableLights(true);

    firebase.notifications().android.createChannel(highPriorityChannel);

    // Request notification permissions from the user
    firebase.messaging().requestPermission({
      sound: true,
      alert: true,
      badge: true,
    });
  }, []);

  // Rest of your app code...
}

export default App;

3. Platform-Specific Configurations

Android

  • Ensure your AndroidManifest.xml includes these permissions (usually added automatically by rnfirebase, but double-check):
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <!-- For Android 13+ -->
    
  • Make sure your app has a notification icon (ic_notification) in the android/app/src/main/res/drawable folder. This is required for notifications to show up.

iOS

  • Open your project in Xcode, go to your app target > Signing & Capabilities > Background Modes, and check Remote notifications.
  • In your Info.plist, add or verify this entry:
    <key>UIBackgroundModes</key>
    <array>
      <string>remote-notification</string>
    </array>
    
  • Ensure your APNs certificates are correctly set up in the Apple Developer Portal, and that your Firebase project is linked with these certificates.

4. Verify Your Push Notification Payload

Make sure the payload you're sending from Firebase Cloud Messaging includes the right fields:

  • For background/closed state, if you're sending a data payload, your background task will handle displaying the notification (which we set up above).
  • If you're sending a notification payload, Firebase should handle it automatically, but adding a data field ensures consistency across states. Example payload:
    {
      "to": "DEVICE_TOKEN",
      "notification": {
        "title": "Urgent Alert",
        "body": "This is a heads-up notification!"
      },
      "data": {
        "screen": "DetailsScreen",
        "id": "123"
      },
      "priority": "high" // Critical for Android heads-up
    }
    

That should do it! With these changes, your app will display heads-up notifications even when it's in the background or fully closed.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:07:37