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

时间:2020-10-04 14:08:59

标签: javascript firebase react-native push-notification firebase-cloud-messaging

我正在尝试在React本机应用程序中使用@ 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 => {});
     }
   });
 };
}

谁能帮助我解决此问题

4 个答案:

答案 0 :(得分:4)

从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> 

添加

<receiver android:name="io.invertase.firebase.notifications.RNFirebaseNotificationReceiver"></receiver>
<receiver android:enabled="true" android:exported="true"  android:name="io.invertase.firebase.notifications.RNFirebaseNotificationsRebootReceiver"></receiver>

答案 1 :(得分:1)

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

答案 2 :(得分:0)

迈克哈迪实际上是对的。

我遇到了这个问题,因为我遵循了旧教程。

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

  <!-- [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] -->

我希望这会帮助其他人:)

答案 3 :(得分:0)

 <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>