如何解决无法从Firebase控制台接收推送通知React Native Android 确保您已进行了预配置:
我正在尝试从最近5天开始解决此问题,但是我不确定自己做错了什么。我已遵循https://www.youtube.com/watch?v=dyAwv9HLS60中提到的说明。但无法从Firebase控制台接收任何通知。虽然当我尝试使用设备令牌发送测试通知时。我在设备上收到通知。我不确定自己在做什么错。首先,我认为这是因为我启用了Hermes引擎,但是即使将其设置为false,我也无法接收通知。
环境
- 本机0.63.2
- “ react-native-push-notification”:“ ^ 5.1.1”
- “ @ react-native-firebase / app”:“ ^ 8.4.2”,
- “ @ react-native-firebase / messaging”:“ ^ 7.8.6”,
我的app / build.gradle
apply plugin: "com.android.application"
apply plugin: 'com.google.gms.google-services'
import com.android.build.OutputFile
project.ext.react = [
enableHermes: true,// clean and rebuild if changing
]
apply from: "../../node_modules/react-native/react.gradle"
def enableSeparateBuildPerCPUArchitecture = false
/**
* Run Proguard to shrink the Java bytecode in release builds.
*/
def enableProguardInReleaseBuilds = false
/**
* The preferred build flavor of JavaScriptCore.
*
* For example,to use the international variant,you can use:
* `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
*
* The international variant includes ICU i18n library and necessary data
* allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
* give correct results when using with locales other than en-US. Note that
* this variant is about 6MiB larger per architecture than default.
*/
def jscFlavor = 'org.webkit:android-jsc:+'
/**
* Whether to enable the Hermes VM.
*
* This should be set on project.ext.react and mirrored here. If it is not set
* on project.ext.react,JavaScript will not be compiled to Hermes Bytecode
* and the benefits of using Hermes will therefore be sharply reduced.
*/
def enableHermes = project.ext.react.get("enableHermes",false);
android {
compileSdkVersion rootProject.ext.compileSdkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
multiDexEnabled true
applicationId "com.fatemicreators.fmbamravati"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true,also generate a universal APK
include "armeabi-v7a","x86","arm64-v8a","x86_64"
}
}
signingConfigs {
debug {
storeFile file('debug.keystore')
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
}
}
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
// Caution! In production,you need to generate your own keystore file.
// see https://reactnative.dev/docs/signed-apk-android.
signingConfig signingConfigs.debug
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"),"proguard-rules.pro"
}
}
// applicationVariants are e.g. debug,release
applicationVariants.all { variant ->
variant.outputs.each { output ->
// For each separate APK per architecture,set a unique version code as described here:
// https://developer.android.com/studio/build/configure-apk-splits.html
def versionCodes = ["armeabi-v7a": 1,"x86": 2,"arm64-v8a": 3,"x86_64": 4]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug,universal-release variants
output.versionCodeOverride =
versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
}
}
}
}
dependencies {
implementation fileTree(dir: "libs",include: ["*.jar"])
//noinspection GradleDynamicVersion
implementation "com.facebook.react:react-native:+" // From node_modules
implementation 'com.google.firebase:firebase-analytics:17.5.0'
implementation 'com.android.support:multidex:1.0.3'
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
exclude group:'com.facebook.fbjni'
}
debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
exclude group:'com.squareup.okhttp3',module:'okhttp'
}
debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
}
if (enableHermes) {
def hermesPath = "../../node_modules/hermes-engine/android/";
debugImplementation files(hermesPath + "hermes-debug.aar")
releaseImplementation files(hermesPath + "hermes-release.aar")
} else {
implementation jscFlavor
}
}
// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.compile
into 'libs'
}
apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
我的FCMService.js
import messaging from '@react-native-firebase/messaging'
import { Platform } from 'react-native';
class FCMService {
register = (onRegister,onNotification,onOpenNotification) => {
this.checkPermission(onRegister)
this.createNotificationListeners(onRegister,onOpenNotification)
}
registerAppWithFCM = async () => {
if (Platform.OS === 'ios') {
await messaging().registerDeviceForRemoteMessages();
await messaging().setAutoInitEnabled(true)
}
}
checkPermission = (onRegister) => {
messaging().hasPermission()
.then(enabled => {
if (enabled) {
// User has permissions
this.getToken(onRegister)
} else {
// User doesn't have permission
this.requestPermission(onRegister)
}
}).catch(error => {
console.log("[FCMService] Permission rejected ",error)
})
}
getToken = (onRegister) => {
messaging().getToken()
.then(fcmToken => {
if (fcmToken) {
onRegister(fcmToken)
} else {
console.log("[FCMService] User does not have a device token")
}
}).catch(error => {
console.log("[FCMService] getToken rejected ",error)
})
}
requestPermission = (onRegister) => {
messaging().requestPermission()
.then(() => {
this.getToken(onRegister)
}).catch(error => {
console.log("[FCMService] Request Permission rejected ",error)
})
}
deleteToken = () => {
console.log("[FCMService] deleteToken ")
messaging().deleteToken()
.catch(error => {
console.log("[FCMService] Delete token error ",error)
})
}
createNotificationListeners = (onRegister,onOpenNotification) => {
// When the application is running,but in the background
messaging()
.onNotificationOpenedApp(remoteMessage => {
console.log('[FCMService] onNotificationOpenedApp Notification caused app to open from background state:',remoteMessage)
if (remoteMessage) {
const notification = remoteMessage.notification
onOpenNotification(notification)
// this.removeDeliveredNotification(notification.notificationId)
}
});
// When the application is opened from a quit state.
messaging()
.getInitialNotification()
.then(remoteMessage => {
console.log('[FCMService] getInitialNotification Notification caused app to open from quit state:',remoteMessage)
if (remoteMessage) {
const notification = remoteMessage.notification
onOpenNotification(notification)
// this.removeDeliveredNotification(notification.notificationId)
}
});
// Foreground state messages
this.messageListener = messaging().onMessage(async remoteMessage => {
console.log('[FCMService] A new FCM message arrived!',remoteMessage);
if (remoteMessage) {
let notification = null
if (Platform.OS === 'ios') {
notification = remoteMessage.data.notification
} else {
notification = remoteMessage.notification
}
onNotification(notification)
}
});
// Triggered when have new token
messaging().onTokenRefresh(fcmToken => {
console.log("[FCMService] New token refresh: ",fcmToken)
onRegister(fcmToken)
})
}
unRegister = () => {
this.messageListener()
}
}
export const fcmService = new FCMService()
解决方法
确保您已进行了预配置:
buildscript {
repositories {
// Check that you have the following line (if not,add it):
google() // Google's Maven repository
}
dependencies {
...
// Add this line
classpath 'com.google.gms:google-services:4.3.3'
}
}
allprojects {
...
repositories {
// Check that you have the following line (if not,add it):
google() // Google's Maven repository
...
}
}
- 然后像下面这样修改
android/app/build.gradle
:
apply plugin: 'com.android.application'
// Add this line
apply plugin: 'com.google.gms.google-services'
dependencies {
// add the Firebase SDK for Google Analytics
implementation 'com.google.firebase:firebase-analytics:17.5.0'
// add SDKs for any other desired Firebase products
// https://firebase.google.com/docs/android/setup#available-libraries
}