无法从Firebase控制台接收推送通知React Native Android 确保您已进行了预配置:

如何解决无法从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()

解决方法

确保您已进行了预配置:

  1. enter image description here
  2. 您必须在android/build.gradle中添加以下内容 (我猜您根据您的描述缺少此内容)
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
    ...
  }
}
  1. 然后像下面这样修改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
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?