最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - App crashes after receiving notification using @react-native-firebasemessaging - Stack Overflow

programmeradmin4浏览0评论

Iam trying to implement notification using @react-native-firebase/messaging in react native app.The App returns the FCM token ,but when a notification is received the app closes.

I got below error in crashlytics

Unable to instantiate service io.invertase.firebase.messaging.RNFirebaseMessagingService: java.lang.ClassNotFoundException: Didn't find class "io.invertase.firebase.messaging.RNFirebaseMessagingService" on path: DexPathList

Below are the library versions used in app.

"@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 mon to all sub-projects/modules.

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


}
repositories {
    google()
    jcenter()
   // mavenCentral()

}
dependencies {
    classpath(".android.tools.build:gradle:3.5.3")
    classpath '.google.gms:google-services:4.2.0'// Google Services plugin
    classpath '.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 '' }
    maven { url "; }

   
 
}

}

app/build.gradle

apply plugin: ".android.application"

import .android.build.OutputFile

def enableHermes = project.ext.react.get("enableHermes", false);

android {
  pileSdkVersion rootProject.extpileSdkVersion

pileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

defaultConfig {
    applicationId ".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 /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:
        // .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 ".facebook.react:react-native:+"  // From node_modules
implementation 'androidx.multidex:multidex:2.0.1'

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

debugImplementation(".facebook.flipper:flipper:${FLIPPER_VERSION}") {
  exclude group:'.facebook.fbjni'
}

debugImplementation(".facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
    exclude group:'.facebook.flipper'
    exclude group:'.squareup.okhttp3', module:'okhttp'
}

debugImplementation(".facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
    exclude group:'.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 pile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
from configurationspile
into 'libs'
 }

apply from: file("../../node_modules/@react-native-munity/cli-platform- 
android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
apply plugin: '.google.gms.google-services'
apply plugin: '.google.firebase.crashlytics'

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

 

Notification code

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 => {});
     }
   });
 };
}

Can anyone help me to fix this issue

Iam trying to implement notification using @react-native-firebase/messaging in react native app.The App returns the FCM token ,but when a notification is received the app closes.

I got below error in crashlytics

Unable to instantiate service io.invertase.firebase.messaging.RNFirebaseMessagingService: java.lang.ClassNotFoundException: Didn't find class "io.invertase.firebase.messaging.RNFirebaseMessagingService" on path: DexPathList

Below are the library versions used in app.

"@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 mon to all sub-projects/modules.

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


}
repositories {
    google()
    jcenter()
   // mavenCentral()

}
dependencies {
    classpath(".android.tools.build:gradle:3.5.3")
    classpath '.google.gms:google-services:4.2.0'// Google Services plugin
    classpath '.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.' }
    maven { url "https://jitpack.io" }

   
 
}

}

app/build.gradle

apply plugin: ".android.application"

import .android.build.OutputFile

def enableHermes = project.ext.react.get("enableHermes", false);

android {
  pileSdkVersion rootProject.ext.pileSdkVersion

pileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

defaultConfig {
    applicationId ".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./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 ".facebook.react:react-native:+"  // From node_modules
implementation 'androidx.multidex:multidex:2.0.1'

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

debugImplementation(".facebook.flipper:flipper:${FLIPPER_VERSION}") {
  exclude group:'.facebook.fbjni'
}

debugImplementation(".facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
    exclude group:'.facebook.flipper'
    exclude group:'.squareup.okhttp3', module:'okhttp'
}

debugImplementation(".facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
    exclude group:'.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 pile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.pile
into 'libs'
 }

apply from: file("../../node_modules/@react-native-munity/cli-platform- 
android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
apply plugin: '.google.gms.google-services'
apply plugin: '.google.firebase.crashlytics'

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

 

Notification code

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 => {});
     }
   });
 };
}

Can anyone help me to fix this issue

Share Improve this question edited Oct 5, 2020 at 10:39 Janaki Narayanan asked Oct 4, 2020 at 14:08 Janaki NarayananJanaki Narayanan 5437 silver badges27 bronze badges 1
  • If you have a problem with react-native-firebase, has it occurred to you to open an issue on the react-native-firebase issue tracker with full details and (for a cloud message crash) the JSON you can send to the FCM REST API to trigger it along with the native stack trace from adb logcat? That would actually get you help :-) – Mike Hardy Commented Dec 20, 2020 at 14:32
Add a ment  | 

4 Answers 4

Reset to default 11

Remove the below code from the AndroidManifest.xml

<service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
        <intent-filter>
            <action android:name=".google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
 <service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService">
        <intent-filter>
            <action android:name=".google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service> 

Just remove those services in the AndroidManifest.xml file and that's it. Don't filter the event intents.

Mike Hardy is actually right.

I got myself into this problem because I have followed old tutorials.

Removing the following services that I have wrongly added resolved the problem:

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

I hope this will help others :)

 <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=".sec.android.provider.badge.permission.WRITE" tools:node="remove" />
    <uses-permission android:name=".oppo.launcher.permission.WRITE_SETTINGS"  tools:node="remove"/>
    <uses-permission android:name=".huawei.android.launcher.permission.WRITE_SETTINGS" tools:node="remove" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>


<application>
<meta-data  android:name=".dieam.reactnativepushnotification.notification_channel_name"
                android:value="YOUR NOTIFICATION CHANNEL NAME"/>
        <meta-data  android:name=".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=".dieam.reactnativepushnotification.notification_foreground"
                    android:value="false"/>
        
        <meta-data  android:name=".dieam.reactnativepushnotification.notification_color"
                    android:resource="@color/white"/> 

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

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

评论列表(0)

  1. 暂无评论