使用@react-native-firebase/messaging 收到通知后应用程序崩溃

Posted

技术标签:

【中文标题】使用@react-native-firebase/messaging 收到通知后应用程序崩溃【英文标题】:App crashes after receiving notification using @react-native-firebase/messaging 【发布时间】:2021-01-19 13:16:58 【问题描述】:

我正在尝试在 react native 应用程序中使用 @react-native-firebase/messaging 实现通知。应用程序返回 FCM 令牌,但是当收到通知时应用程序关闭。

我在 crashlytics 中遇到以下错误

无法实例化服务 io.invertase.firebase.messaging.RNFirebaseMessagingService:java.lang.ClassNotFoundException:在路径:DexPathList 上找不到类“io.invertase.firebase.messaging.RNFirebaseMessagingService”

以下是应用中使用的库版本。

"@react-native-firebase/analytics": "^7.6.7",
"@react-native-firebase/app": "^8.4.3",
"@react-native-firebase/crashlytics": "^8.4.9",
"@react-native-firebase/messaging": "^7.8.11",
"react": "16.13.1",
"react-native": "^0.63.3",

android/build.grade

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript 
ext 
    buildToolsVersion = "30.0.0"
    minSdkVersion = 16
    compileSdkVersion = 30
    targetSdkVersion = 30
    supportLibVersion = "27.0.0"
    // googlePlayServicesVersion = "16.+"
    // androidMapsUtilsVersion = "0.5+"
    // firebaseVersion = "+"
    // firebaseMessagingVersion = "+"



repositories 
    google()
    jcenter()
   // mavenCentral()


dependencies 
    classpath("com.android.tools.build:gradle:3.5.3")
    classpath 'com.google.gms:google-services:4.2.0'// Google Services plugin
    classpath 'com.google.firebase:firebase-crashlytics-gradle:2.3.0'


    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files



allprojects 
repositories 
    google()
    mavenLocal()
    jcenter()
    maven 
        // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
        url("$rootDir/../node_modules/react-native/android")
    
    maven 
        // Android JSC is installed from npm
        url("$rootDir/../node_modules/jsc-android/dist")
     
  //  maven  url 'https://maven.google.com' 
    maven  url "https://jitpack.io" 

   
 



app/build.gradle

apply plugin: "com.android.application"

import com.android.build.OutputFile

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 
    applicationId "com.awrostamani.starterkit"
    minSdkVersion rootProject.ext.minSdkVersion
    targetSdkVersion rootProject.ext.targetSdkVersion
    versionCode project.env.get("ANDROID_VERSION_CODE").toInteger() 
    versionName project.env.get("ANDROID_VERSION_NAME")
    multiDexEnabled true

splits 
    abi 
        reset()
        enable enableSeparateBuildPerCPUArchitecture
        universalApk false  // If true, also generate a universal APK
        include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
    

signingConfigs 
    debug 
       
    
    release 
      
  

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 'androidx.multidex:multidex:2.0.1'

implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
// implementation 'com.android.support:support-annotations:28.0.0'
// implementation 'com.android.support:appcompat-v7:28.0.0'
// implementation 'androidx.appcompat:appcompat:1.0.2'
// implementation 'androidx.annotation:annotation:1.0.2'
// implementation 'me.leolin:ShortcutBadger:1.1.21@aar'
 implementation 'com.google.firebase:firebase-analytics:17.5.0'
 implementation 'com.google.firebase:firebase-crashlytics:17.2.2'
 implementation "com.google.android.gms:play-services-base:16.1.0"
 implementation 'com.google.firebase:firebase-core:16.0.9'
  implementation 'com.google.firebase:firebase-messaging:20.3.0'
  implementation "com.google.android.gms:play-services-gcm:12.+"

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)
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.firebase.crashlytics'

  // Google Play services Gradle plugin
  com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true

 

通知代码

import notifee from "@notifee/react-native";
import messaging from "@react-native-firebase/messaging";

export default class Notifications 
 static onMessageReceived(message) 
 const  type, timestamp  = message.data;

 if (type === "order_shipped") 
  notifee.displayNotification(
    title: "Your order has been shipped",
    body: `Your order was shipped at $new Date(
      Number(timestamp)
    ).toString()!`,
    android: 
      channelId: "orders"
    
  );
 
 

static onMessage = messageHandler => 
alert("test");

  messaging().onMessage(this.onMessageReceived);
;
  static setBackgroundMessageHandler = messageHandler => 
  messaging().setBackgroundMessageHandler(this.onMessageReceived);
  ;
static getToken = async () => 
try 
  const fcmToken = await messaging().getToken();
  Notifications.checkPermission();
  if (fcmToken) return fcmToken;
  else return null;
  catch (err) 
  console.log("--->Token error from Notifications:" + err);
  return null;
 
;

 static onTokenRefresh = refreshHandler => 
return messaging().onTokenRefresh(fcmToken => 
  refreshHandler(fcmToken);
 );
;

static checkPermission = () => 
messaging()
  .hasPermission()
  .then(enabled => 
    if (enabled) 
     else 
      messaging()
        .requestPermission(
          alert: true,
          announcement: false,
          badge: true,
          carPlay: false,
          provisional: false,
          sound: true
        )
        .then(() => )
        .catch(error => );
     
   );
 ;

谁能帮我解决这个问题

【问题讨论】:

如果您对 react-native-firebase 有疑问,您是否想过在 react-native-firebase 问题跟踪器上打开一个包含完整详细信息的问题以及(对于云消息崩溃)您可以将 JSON 发送到 FCM REST API 以触发它以及来自 adb logcat 的本机堆栈跟踪?这实际上会给你帮助:-) 【参考方案1】:

从 AndroidManifest.xml 中删除以下代码

<service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_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> 

【讨论】:

我很惊讶这不在官方 react-native-firebase 文档中 这真的很有帮助 您好!我维护 react-native-firebase。这不在文档中,因为这是一个糟糕的主意,抱歉。这意味着您将不再收到通知事件,因为没有过滤任何意图。 @TuanAnh 根据文档使用当前版本的 react-native-firebase?我是认真的。当前版本的 AndroidManifest 中不需要任何内容​​,并且会收到 Firebase Cloud 消息而不会导致应用崩溃。在此处构建演示的脚本:github.com/mikehardy/rnfbdemo/blob/master/make-demo.sh【参考方案2】:

只需在 AndroidManifest.xml 文件中删除这些服务即可。不要过滤事件意图。

【讨论】:

【参考方案3】:

迈克·哈迪实际上是对的。

我陷入了这个问题,因为我遵循了旧教程。

删除以下我错误添加的服务解决了问题:

  <!-- [START firebase_service] -->
  <service
    android:name=".java.MyFirebaseMessagingService"
    android:exported="false">
    <intent-filter>
      <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
  </service>
  <!-- [END firebase_service] -->

我希望这对其他人有帮助:)

【讨论】:

【参考方案4】:
 <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.VIBRATE" />  
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />  
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <uses-permission android:name="com.sec.android.provider.badge.permission.WRITE" tools:node="remove" />
    <uses-permission android:name="com.oppo.launcher.permission.WRITE_SETTINGS"  tools:node="remove"/>
    <uses-permission android:name="com.huawei.android.launcher.permission.WRITE_SETTINGS" tools:node="remove" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>


<application>
<meta-data  android:name="com.dieam.reactnativepushnotification.notification_channel_name"
                android:value="YOUR NOTIFICATION CHANNEL NAME"/>
        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_channel_description"
                    android:value="YOUR NOTIFICATION CHANNEL DESCRIPTION"/>
        <!-- Change the value to true to enable pop-up for in foreground on receiving remote notifications (for prevent duplicating while showing local notifications set this to false) -->
        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_foreground"
                    android:value="false"/>
        
        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_color"
                    android:resource="@color/white"/> 

        <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationActions" />
        <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" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
                <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
            </intent-filter>
        </receiver>

        <service
            android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
<application>

【讨论】:

以上是关于使用@react-native-firebase/messaging 收到通知后应用程序崩溃的主要内容,如果未能解决你的问题,请参考以下文章

使用 react-native-firebase 创建 Firebase 动态链接失败 - React Native

使用 react-native-firebase 在 React Native 上自定义通知

如何使用 react-native-firebase 在 iOS 设备的推送通知中添加按钮?

在设备上使用 react-native-firebase 检测文本要求计费

如何使用 react-native-firebase v5 正确设置前台通知?

错误:捆绑失败 - 尝试解析模块“react-native-firebase”时