我已经在我的应用中添加了 react-native-firebase,但是当从 Firebase 控制台或 Postman 发送消息时,应用会关闭。当我查看调试窗口或使用反应原生日志android时,没有错误消息,应用程序只是关闭。未提供任何信息。
我的主要文件称为 Base.js:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Animated, Dimensions, StyleSheet, Platform, Image, Text, View, ScrollView, TouchableOpacity, AsyncStorage } from 'react-native';
import rnfirebase, { Notification, RemoteMessage, NotificationOpen } from 'react-native-firebase';
import { Actions } from 'react-native-router-flux';
import DeviceInfo from 'react-native-device-info-2';
import { Button, CardSection, Card } from './components/common';
import { getUserInfo, storeToken } from './actions';
const SCREEN_WIDTH = Dimensions.get('window').width;
const GLOBAL = require('./Globals');
class Base extends Component {
constructor(props){
super(props);
this.state={
emergencyNotification: '',
user:{
name: 'nSideMobileAdmin'
}
};
}
async componentDidMount() {
getUserInfo();
rnfirebase.messaging().getToken().then((fcmToken) => {
if (fcmToken !== null) {
GLOBAL.FCMTOKEN = fcmToken;
console.log(`Token obtained: ${fcmToken}`);
if (!GLOBAL.TOKENSTORED) {
GLOBAL.TOKENSTORED = true;
storeToken(fcmToken, 'General')
}
AsyncStorage.setItem('rnfb-token', fcmToken);
} else {
console.log('Unable to get token.');
}
rnfirebase.messaging().hasPermission().then((enabled) => {
if (enabled) {
console.log(`Messaging Enabled`);
const channel = new rnfirebase.notifications.Android.Channel('nSideMobile', 'nSide Channel', rnfirebase.notifications.Android.Importance.Max)
.setDescription('nSide Mobile Channel');
// Create the channel
rnfirebase.notifications().android.createChannel(channel);
this.messageListener = rnfirebase.messaging().onMessage((message: RemoteMessage) => {
console.log(`Message Recieved: ${JSON.stringify(message)}`);
console.log(`GLOBAL NOTIFICATION: ${JSON.stringify(message)}`);
});
} else {
try {
rnfirebase.messaging().requestPermission().then((response) => {
console.log('User is authorized');
});
} catch (error) {
console.log('User has rejected permissions');
}
}
//
// this.notificationDisplayedListener = rnfirebase.notifications().onNotificationDisplayed((notification: Notification) => {
// console.log(`Notification Displayed: ${JSON.stringify(notification.body)}`);
// pushNotification(notification, this.state.user);
// this.setState({ emergencyNotification: notification });
// //Actions.Emergency();
// });
// this.notificationListener = rnfirebase.notifications().onNotification((notification: Notification) => {
// pushNotification(notification, this.state.user);
// this.setState({ emergencyNotification: notification });
// //Actions.Emergency();
// });
// this.notificationOpenedListener = rnfirebase.notifications().onNotificationOpened((notificationOpen: NotificationOpen) => {
// const action = notificationOpen.action;
// const notification: Notification = notificationOpen.notification;
// console.log(`App Opened by Notification with message: : ${notification.body}`);
// pushNotification(notification, this.state.user);
// this.setState({ emergencyNotification: notification });
// //Actions.Emergency();
// });
// rnfirebase.notifications().getInitialNotification().then((notificationOpen) => {
// if (notificationOpen) {
// const action = notificationOpen.action;
// const notification: Notification = notificationOpen.notification;
// console.log(`App Opened by Initial Notification with Message: : ${notification.body}`);
// pushNotification(notification, this.state.user);
// this.setState({ emergencyNotification: notification });
// //Actions.Emergency();
// }
// });
});
});
}
pushNotification(notification, user){
console.log(`${JSON.stringify(user)}`);
pushNotification(notification, user);
}
async onLoginButtonPress() {
try {
const token = await AsyncStorage.getItem('token');
if (token === null || token === 'LoggedOut') {
Actions.login();
} else {
console.log('LoggedIn');
GLOBAL.USER.token = token;
GLOBAL.USER.id = await AsyncStorage.getItem('userID');
//console.log(`Logged in ${GLOBAL.USER.id} with token: ${GLOBAL.USER.token}`);
Actions.menu();
}
} catch (error) {
//We'll deal with the error later
}
}
onRegisterButtonPress() {
Actions.register();
}
onChatButtonPress() {
Actions.chatLogin();
}
getDeviceInfo() {
const deviceName = DeviceInfo.getDeviceId();
this.setState(deviceName: deviceName);
}
componeWillUnmount() {
this.onTokenRefreshListener();
this.messageListener();
this.notificationDisplayedListener();
this.notificationListener();
this.notificationOpenedListener();
}
render() {
return (
<Card>
<CardSection>
<Image
source={require('../assets//hsschool.jpg')}
style={{ width: SCREEN_WIDTH, height: SCREEN_WIDTH }}
/>
</CardSection>
<CardSection>
<Image
source={require('../assets/logo.jpg')}
style={{ width: SCREEN_WIDTH * 0.95, height: SCREEN_WIDTH * 0.255 }}
/>
</CardSection>
<CardSection>
<Button onPressAction={this.onLoginButtonPress.bind(this)}>
Login
</Button>
<Button onPressAction={this.onRegisterButtonPress.bind(this)}>
Register
</Button>
<Button onPressAction={this.onChatButtonPress.bind(this)}>
Chat
</Button>
</CardSection>
<View style={styles.modules}>
<Text style={styles.modulesHeader}>The following Firebase modules are enabled:</Text>
{rnfirebase.admob.nativeModuleExists && <Text style={styles.module}>Admob</Text>}
{rnfirebase.analytics.nativeModuleExists && <Text style={styles.module}>Analytics</Text>}
{rnfirebase.auth.nativeModuleExists && <Text style={styles.module}>Authentication</Text>}
{rnfirebase.firestore.nativeModuleExists && <Text style={styles.module}>Cloud Firestore</Text>}
{rnfirebase.messaging.nativeModuleExists && <Text style={styles.module}>Cloud Messaging</Text>}
{rnfirebase.links.nativeModuleExists && <Text style={styles.module}>Dynamic Links</Text>}
{rnfirebase.iid.nativeModuleExists && <Text style={styles.module}>Instance ID</Text>}
{rnfirebase.notifications.nativeModuleExists && <Text style={styles.module}>Notifications</Text>}
{rnfirebase.perf.nativeModuleExists && <Text style={styles.module}>Performance Monitoring</Text>}
{rnfirebase.database.nativeModuleExists && <Text style={styles.module}>Realtime Database</Text>}
{rnfirebase.config.nativeModuleExists && <Text style={styles.module}>Remote Config</Text>}
{rnfirebase.storage.nativeModuleExists && <Text style={styles.module}>Storage</Text>}
</View>
</Card>
);
}
}
const mapStateToProps = (state) => {
const {
emergencyNotification } = state.session;
return {
emergencyNotification };
};
const mapDispatchToProps = (dispatch) => ({
getUserInfo: () => {
dispatch(getUserInfo());
},
storeToken: () => {
storeToken(storeToken());
}
});
export default connect(mapStateToProps, mapDispatchToProps)(Base);
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
modules: {
margin: 20,
transform: [{ scale: 0 }]
},
module: {
fontSize: 14,
marginTop: 4,
textAlign: 'center',
},
cardStyle: {
borderWidth: 1,
borderRadius: 2,
borderColor: '#ddd',
borderBottomWidth: 0,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.3,
shadowRadius: 2,
elevation: 1,
marginLeft: 5,
marginRight: 5,
marginTop: 10
}
});
我的包.json:
{
"name": "nsidemobile",
"version": "0.1.0",
"private": true,
"devDependencies": {
"@babel/core": "^7.0.0-beta",
"babel-core": "^7.0.0-beta",
"babel-jest": "22.0.6",
"fs-extra": "^4.0.2",
"jest": "^23.2.0",
"react-test-renderer": "16.2.0",
"replace-in-file": "^3.0.0"
},
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"rename": "node ./bin/rename.js",
"start": "react-native start",
"test": "jest"
},
"jest": {
"preset": "react-native"
},
"dependencies": {
"babel-cli": "^6.26.0",
"eslint-config-rallycoding": "^3.2.0",
"eslint-plugin-prettier": "^2.6.2",
"fbjs": "^0.8.16",
"firebase": "^5.3.1",
"lodash": "^4.17.10",
"moment": "^2.22.2",
"node-fetch": "^2.2.0",
"prop-types": "^15.6.2",
"react": "^16.4.2",
"react-native": "^0.56.0",
"react-native-camera-kit": "^6.2.6",
"react-native-communications": "^2.2.1",
"react-native-device-info-2": "^0.1.1",
"react-native-elements": "^0.19.1",
"react-native-firebase": "^4.3.6",
"react-native-fs": "^2.11.15",
"react-native-google-signin": "git+https://github.com/invertase/react-native-google-signin.git#v0.12.1",
"react-native-image-base64": "^0.1.3",
"react-native-image-resizer": "^1.0.0",
"react-native-keyboard-aware-scroll-view": "^0.6.0",
"react-native-keyboard-spacer": "^0.4.1",
"react-native-loader": "^1.2.1",
"react-native-maps": "^0.21.0",
"react-native-push-notification": "^3.1.1",
"react-native-push-notifications": "^3.0.10",
"react-native-router-flux": "^4.0.0-beta.31",
"react-native-vector-icons": "^5.0.0",
"react-navigation": "^2.11.2",
"react-redux": "^5.0.7",
"redux": "^4.0.0",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.3.0",
"styled-components": "^3.4.2"
}
}
我的申请.js:
package io.nside.nsidemobile;
import android.app.Application;
import com.facebook.react.ReactApplication;
import com.wix.RNCameraKit.RNCameraKitPackage;
import fr.snapp.imagebase64.RNImgToBase64Package;
import fr.bamlab.rnimageresizer.ImageResizerPackage;
import com.oblador.vectoricons.VectorIconsPackage;
import com.rnfs.RNFSPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import com.airbnb.android.react.maps.MapsPackage;
import io.invertase.firebase.RNFirebasePackage;
// optional packages - add/remove as appropriate
import io.invertase.firebase.admob.RNFirebaseAdMobPackage; //Firebase AdMob
import io.invertase.firebase.analytics.RNFirebaseAnalyticsPackage; // Firebase Analytics
import io.invertase.firebase.auth.RNFirebaseAuthPackage; // Firebase Auth
import io.invertase.firebase.config.RNFirebaseRemoteConfigPackage; // Firebase Remote Config
import io.invertase.firebase.database.RNFirebaseDatabasePackage; // Firebase Realtime Database
import io.invertase.firebase.firestore.RNFirebaseFirestorePackage; // Firebase Firestore
import io.invertase.firebase.instanceid.RNFirebaseInstanceIdPackage; // Firebase Instance ID
import io.invertase.firebase.links.RNFirebaseLinksPackage; // Firebase Dynamic Links
import io.invertase.firebase.messaging.RNFirebaseMessagingPackage; // Firebase Cloud Messaging
import io.invertase.firebase.notifications.RNFirebaseNotificationsPackage; // Firebase Notifications
import io.invertase.firebase.perf.RNFirebasePerformancePackage; // Firebase Performance
import io.invertase.firebase.storage.RNFirebaseStoragePackage; // Firebase Storage
import io.invertase.firebase.fabric.crashlytics.RNFirebaseCrashlyticsPackage; // Crashlytics
import java.util.Arrays;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new VectorIconsPackage(),
new RNFSPackage(),
new ImageResizerPackage(),
new MapsPackage(),
new RNFirebasePackage(),
// add/remove these packages as appropriate
new RNFirebaseAdMobPackage(),
new RNFirebaseAnalyticsPackage(),
new RNFirebaseAuthPackage(),
new RNFirebaseCrashlyticsPackage(),
new RNFirebaseDatabasePackage(),
new RNFirebaseFirestorePackage(),
new RNFirebaseInstanceIdPackage(),
new RNFirebaseLinksPackage(),
new RNFirebaseMessagingPackage(),
new RNFirebaseNotificationsPackage(),
new RNFirebasePerformancePackage(),
new RNFirebaseRemoteConfigPackage(),
new RNFirebaseStoragePackage(),
new RNCameraKitPackage()
);
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
}
}
我的安卓清单.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.nside.nsidemobile"
android:versionCode="1"
xmlns:tools="http://schemas.android.com/tools"
android:versionName="1.0">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<permission
android:name="io.nside.nsidemobile.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="io.nside.nsidemobile.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:name=".MainApplication"
android:allowBackup="true"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
<service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
<receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="io.nside.nsidemobile" />
</intent-filter>
</receiver>
<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationRegistrationService"/>
<service
android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<meta-data
tools:replace="android:value"
android:name="android.support.VERSION"
android:value="25.3.1" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyAMsevtE97707k9dzhgvGuMbmK6SHN6I-Q"/>
<!-- Set custom default icon. This is used when no icon is set for incoming notification messages. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_stat_ic_notification" />
</application>
</manifest>
在我看来,这听起来像是我在admob Firebase的模块中遇到的问题。
尝试注释链接到 admob 的所有代码,然后重新生成。 如果问题消失,您应该验证 firebase admob 配置,查看 app/src/main/AndroidManifest.xml 包含以下内容,替换您的应用 ID 来自 AdMob 控制台:
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub.............."/>
<uses-library
android:name="org.apache.http.legacy" android:required="false"/>
在这里,您将找到有关此主题的完整详细信息 https://rnfirebase.io/docs/v5.x.x/admob/android
再见