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

Expo推送令牌获取失败:FirebaseApp未初始化问题求助

Expo推送通知无法获取令牌:Firebase未初始化报错排查

问题描述

配置Expo推送通知时无法获取推送令牌,已尝试初始化Firebase但仍报错,错误信息如下:

ERROR Error getting push token [Error: Call to function 'ExpoPushTokenManager.getDevicePushTokenAsync' has been rejected.
→ Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.dev_suhrid.dhcloudkitchen. Make sure to call FirebaseApp.initializeApp(Context) first.]

相关代码:

import React, { useEffect, useState, useRef } from 'react';
import {
  StyleSheet,
  Text,
  View,
  StatusBar,
  TouchableOpacity,
  Alert,
  BackHandler,
  Platform
} from 'react-native';
import NetInfo from '@react-native-community/netinfo';
import { MaterialIcons } from '@expo/vector-icons';
import { WebView } from 'react-native-webview';
import * as Notifications from 'expo-notifications';
import Constants from 'expo-constants';
import firebase from '@react-native-firebase/app';

const firebaseConfig = {
  apiKey: "your-api-key",
  authDomain: "your-app-id.firebaseapp.com",
  projectId: "your-project-id",
  storageBucket: "your-app-id.appspot.com",
  messagingSenderId: "your-messaging-sender-id",
  appId: "your-app-id",
  measurementId: "your-measurement-id"
};

if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
}

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: false,
  }),
});

// Function to register for push notifications
async function registerForPushNotificationsAsync() {
  let token;
  const { status: existingStatus } = await Notifications.getPermissionsAsync();
  let finalStatus = existingStatus;

  if (existingStatus !== 'granted') {
    const { status } = await Notifications.requestPermissionsAsync();
    finalStatus = status;
  }

  if (finalStatus !== 'granted') {
    alert('Failed to get push token for push notification!');
    return;
  }

  try {
    token = (await Notifications.getExpoPushTokenAsync()).data;
    console.log('Expo Push Token:', token);
  } catch (error) {
    console.error('Error getting push token', error);
  }

  if (Platform.OS === 'android') {
    Notifications.setNotificationChannelAsync('default', {
      name: 'default',
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: '#FF231F7C',
    });
  }

  return token;
}

export default function App() {
  const [isConnected, setIsConnected] = useState(true);
  const [webViewError, setWebViewError] = useState(null);
  const webViewRef = useRef(null);
  const [canGoBack, setCanGoBack] = useState(false);
  const [expoPushToken, setExpoPushToken] = useState('');
  const [notification, setNotification] = useState(false);
  const notificationListener = useRef();
  const responseListener = useRef();

  useEffect(() => {
    registerForPushNotificationsAsync().then(token => setExpoPushToken(token));

    notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
      setNotification(notification);
    });

    responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
      console.log(response);
    });

    return () => {
      Notifications.removeNotificationSubscription(notificationListener.current);
      Notifications.removeNotificationSubscription(responseListener.current);
    };
  }, []);

  useEffect(() => {
    const backHandler = BackHandler.addEventListener('hardwareBackPress', () => {
      if (canGoBack && webViewRef.current) {
        webViewRef.current.goBack();
        return true;
      } else {
        Alert.alert(
          'Exit App',
          'Are you sure you want to exit?',
          [
            { text: 'Cancel', onPress: () => {} },
            { text: 'Exit', onPress: () => BackHandler.exitApp() }
          ],
          { cancelable: true }
        );
        return true;
      }
    });
    return () => {
      backHandler.remove();
    };
  }, [canGoBack]);

  useEffect(() => {
    const unsubscribe = NetInfo.addEventListener(state => {
      setIsConnected(state.isConnected);
    });
    return () => {
      unsubscribe();
    };
  }, []);

  const handleWebViewError = (error) => {
    setWebViewError(error);
  };

  const handleReload = () => {
    setWebViewError(null);
  };

  StatusBar.setBackgroundColor('#fff');
  StatusBar.setBarStyle('dark-content');

  return (
    <View style={styles.container}>
      {!isConnected ? (
        <View style={styles.offlineContainer}>
          <MaterialIcons name="signal-wifi-statusbar-connected-no-internet-4" size={100} color="#ff6347" />
          <Text style={styles.offlineText}>No Internet Connection</Text>
          <Text style={styles.tryAgainText}>Please check your internet connection and try again.</Text>
          <TouchableOpacity style={styles.reloadButton} onPress={handleReload}>
            <Text style={styles.reloadButtonText}>Reload</Text>
          </TouchableOpacity>
        </View>
      ) : (
        <WebView
          ref={webViewRef}
          source={{ uri: 'https://dhcloudkitchen.in/userApp/login' }}
          style={{ flex: 1 }}
          onError={handleWebViewError}
          onNavigationStateChange={navState => setCanGoBack(navState.canGoBack)}
        />
      )}
      {webViewError && (
        <View style={styles.errorContainer}>
          <Text style={styles.errorText}>Error loading page: {webViewError}</Text>
        </View>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
 
});

解决方案

1. 调整Firebase初始化时机

Android环境下需确保Firebase在React Native上下文完全初始化后执行,将初始化逻辑移到组件的useEffect中:

export default function App() {
  // ...其他状态定义
  useEffect(() => {
    // 先初始化Firebase
    if (!firebase.apps.length) {
      try {
        firebase.initializeApp(firebaseConfig);
        console.log('Firebase初始化成功');
      } catch (err) {
        console.error('Firebase初始化失败:', err);
      }
    }
    // 再调用推送注册函数
    registerForPushNotificationsAsync().then(token => setExpoPushToken(token));
    
    // ...其他监听逻辑
  }, []);
}

2. 验证Android配置文件

  • 确认android/app/google-services.json文件与Firebase控制台下载的完全一致,且放置路径正确。
  • 检查gradle配置:
    • 在android/build.gradle的dependencies中添加:
      classpath 'com.google.gms:google-services:4.3.15'
      
    • 在android/app/build.gradle末尾添加:
      apply plugin: 'com.google.gms.google-services'
      

3. 确保Expo与Firebase兼容

  • 若使用Expo Managed Workflow,安装expo-firebase-core:
    expo install expo-firebase-core
    
    并在app.json中配置:
    "expo": {
      "android": {
        "googleServicesFile": "./google-services.json"
      },
      "plugins": [
        [
          "expo-firebase-core",
          {
            "firebaseVersion": "19.0.0"
          }
        ]
      ]
    }
    

4. 清理缓存重建项目

  • 清理Expo缓存:expo r -c
  • 清理Android构建缓存:cd android && ./gradlew clean && cd ..
  • 重新构建项目:expo run:android

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 08:54:52