我尝试设置推送通知,但收到错误消息。我不明白为什么会收到此错误。 错误 获取推送令牌时出错 [错误:对函数“ExpoPushTokenManager.getDevicePushTokenAsync”的调用已被拒绝。 → 原因:java.lang.IllegalStateException:默认 FirebaseApp 在此进程 com.dev_suhrid.dhcloudkitchen 中未初始化。确保首先调用 FirebaseApp.initializeApp(Context)。]
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({
});
如果尚未解决...您必须将以下行添加到您的 gradle 文件中:
android/app/build.gradle
:apply plugin: "com.android.application"
apply plugin: "com.google.gms.google-services" // add this line
apply plugin: "org.jetbrains.kotlin.android"
apply plugin: "com.facebook.react"
android/build.gradle
:dependencies {
classpath 'com.google.gms:google-services:4.3.3' // add this line
classpath('com.android.tools.build:gradle')
classpath('com.facebook.react:react-native-gradle-plugin')
classpath('org.jetbrains.kotlin:kotlin-gradle-plugin')
}
您可以使用 expo 插件动态添加这些行,以确保在构建应用程序时添加这些行