当前位置: 首页 > 知识库问答 >
问题:

无法从firebase控制台接收推送通知(React Native Android)

章振
2023-03-14

在过去的5天里,我一直在努力解决这个问题,但我不确定自己做错了什么。我已按照本手册中提到的说明进行操作https://www.youtube.com/watch?v=dyAwv9HLS60.但无法从firebase控制台接收任何通知。虽然当我尝试用设备令牌从发送测试通知时。我在设备上收到通知。我不确定我做错了什么。首先,我认为这是因为我启用了Hermes引擎,但即使将其设置为false,我也无法接收通知。

环境类

  • 反应本机0.63.2

我的应用/构建。格拉德尔

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)

我的FCM服务。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, onNotification, 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, onNotification, 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个答案

孔斌
2023-03-14
  1. 您必须在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
    ...
  }
}
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
}
 类似资料:
  • 我已经试着调试Firebase推送通知相当长时间了,但没有得到任何运气。我相信我已经正确地设置了临时配置文件和APNs证书。当我不包含方法时 当应用程序从Firebase通知控制台发送时,它会在前台接收通知,因为它会被打印出来,但它不会在后台接收通知。

  • 消息“成功订阅到广播频道。”在应用程序启动时打印。但是当我使用parse.com上的“发送推送通知”功能时,我的手机没有收到任何推送通知。 为什么不起作用?

  • 我看过这个问题。我有完全相同的问题,但我有来自Thawte的有效ssl证书。我只使用id、type和address属性进行了观察请求,如这里所述。我的address属性类似于 我甚至没有收到同步消息。会出什么问题?

  • 当我的应用程序处于打开状态时,我正在通过onMessageReceived(Remotemessage mesg)获得推送通知。如果我的应用程序处于Kilded状态,我将收到推送通知,但不是从onMessageReceived()获得的。 意思是,在收到推送通知后,根据通知中的数据,我需要重定向页面,当通知点击时。如果应用程序在前景工作良好。当我杀人的时候,我在托盘上收到通知,但当我点击通知时,它

  • 我正在使用API explorer和Chrome Advanced Rest Client根据给定的示例观看事件资源。https://developers.google.com/google-apps/calendar/v3/push#watch_request_examples 要求 回应 > 我在google上搜索了这个问题,但找不到太多帮助。 有人能告诉我,请求有什么问题吗?

  • 我在google cloud上使用推送通知,但出于某种原因,我无法在模拟器上接收推送通知。 但是,当我在实际设备上测试时,相同的应用程序确实会收到通知。