Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

App crashes after receiving notification using @react-native-firebase/messaging

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

 

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

like image 761
Janaki Narayanan Avatar asked Mar 03 '23 00:03

Janaki Narayanan


2 Answers

Remove the below code from the 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> 
like image 71
Janaki Narayanan Avatar answered Mar 11 '23 14:03

Janaki Narayanan


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

like image 23
ivan avila Avatar answered Mar 11 '23 14:03

ivan avila