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

React Native Android应用无法读取Firebase消息并存储至AsyncStorage

Fixing Firebase Message Reading to Save to AsyncStorage in React Native

Hey there! I see you're new to React Native and have FCM set up successfully—great start! The issue you're facing (not being able to read incoming Firebase messages to save them with AsyncStorage) is super common, so let's break down how to fix it step by step.

First, Understand the Core Issue

When you send a notification from the Firebase Console, it's usually a notification-only message. On iOS/Android, these are handled by the system directly when your app is in the background—meaning they'll show up in the notification tray, but won't trigger your JavaScript listener. To capture the message content (and save it to AsyncStorage), you need to either:

  • Send a data-only message, or
  • Send a combined notification + data message (so your listener can access the data even when the app is backgrounded)

Step-by-Step Fix with Code Example

Let's update your componentDidMount logic to properly listen for all notification events, capture the message data, and save it to AsyncStorage. Here's a complete, working example:

import React, { Component } from 'react';
import { Platform, AsyncStorage } from 'react-native';
import FCM, { FCMEvent, FCMNotificationResult } from 'react-native-fcm';

class YourComponent extends Component {
  async componentDidMount() {
    // 1. Request notification permissions (required for iOS; Android handles this automatically)
    const permissions = await FCM.requestPermissions({
      badge: true,
      sound: true,
      alert: true
    });
    console.log('Notification permissions:', permissions);

    // 2. Set up a listener for ALL incoming notifications
    FCM.on(FCMEvent.Notification, async (notification) => {
      // Log the full notification object to debug what you're receiving
      console.log('Received notification data:', notification);

      // 3. Save the notification to AsyncStorage
      try {
        // Get existing notifications from storage (or initialize an empty array)
        let savedNotifications = await AsyncStorage.getItem('appNotifications');
        savedNotifications = savedNotifications ? JSON.parse(savedNotifications) : [];

        // Add the new notification with a timestamp for organization
        const newNotification = {
          title: notification.title || 'No Title',
          body: notification.body || 'No Body',
          data: notification.data || {},
          receivedAt: new Date().toISOString()
        };
        savedNotifications.push(newNotification);

        // Save the updated array back to AsyncStorage
        await AsyncStorage.setItem('appNotifications', JSON.stringify(savedNotifications));
        console.log('Notification saved successfully!');
      } catch (error) {
        console.error('Failed to save notification:', error);
      }

      // 4. iOS only: Tell the system you've handled the notification
      if (Platform.OS === 'ios') {
        notification.finish(FCMNotificationResult.NoData);
      }
    });

    // Optional: Listen for token refreshes (useful for sending notifications to specific devices)
    FCM.on(FCMEvent.RefreshToken, (newToken) => {
      console.log('FCM token refreshed:', newToken);
      // You can send this token to your backend here
    });

    // Get the initial FCM token on app start
    const initialToken = await FCM.getFCMToken();
    console.log('Initial FCM token:', initialToken);
  }

  // Don't forget to clean up listeners when the component unmounts!
  componentWillUnmount() {
    FCM.off(FCMEvent.Notification);
    FCM.off(FCMEvent.RefreshToken);
  }

  render() {
    // Your component render logic here
    return null;
  }
}

export default YourComponent;

Key Things to Remember

  • Test with Data Messages: When sending from the Firebase Console, go to the Advanced options tab and add custom key-value pairs under Custom data. This ensures your listener will receive the message even when the app is in the background.
  • Android Background Handling: For Android, make sure your AndroidManifest.xml has the correct FCM service declarations (react-native-fcm usually configures this automatically, but double-check if you're still having issues).
  • AsyncStorage Limitations: AsyncStorage only stores strings, so always stringify your notification array before saving, and parse it when retrieving.

That should do it! With this setup, you'll be able to capture every incoming notification and save it to your app's storage for later access.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:22:56