React-native-firebase: FCM Message crashes Android app

Created on 5 Oct 2018  路  10Comments  路  Source: invertase/react-native-firebase

RNFMessagingService: onMessageReceived event received
FATAL EXCEPTION: Firebase-RNFirebaseMessagingService
Process: com.starbeat, PID: 26367
java.lang.ClassCastException: com.starbeat.MainApplication cannot be cast to com.facebook.react.bridge.ReactContext
at io.invertase.firebase.Utils.isAppInForeground(Utils.java:155)
at io.invertase.firebase.messaging.RNFirebaseMessagingService.onMessageReceived(RNFirebaseMessagingService.java:34)
at com.google.firebase.messaging.FirebaseMessagingService.zzd(Unknown Source:60)
at com.google.firebase.iid.zzg.run(Unknown Source:4)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at com.google.android.gms.common.util.concurrent.zza.run(Unknown Source:7)
at java.lang.Thread.run(Thread.java:764)

Config wise I followed the documentation.
app/build.gradle

    implementation "com.google.firebase:firebase-core:16.0.3"
    implementation "com.google.firebase:firebase-database:16.0.1"
    implementation "com.google.firebase:firebase-messaging:17.3.0"
    implementation "com.google.android.gms:play-services-base:15.0.1"

Environment

Android
RN: v0.56
RNFirebase: v5.0.0-rc4
Module: FCM - Messaging

Notification works fine. Messaging crashes.

I trigger notifications / messages with the web API through https://fcm.googleapis.com/fcm/send.

Crashes in both foreground and background(minimized, not killed). App does not include the headless JS thing to listen for messages in the background.

Bug Android Messaging

All 10 comments

same with me

@arivanandan @gifary this is fixed on the full v5 release. Please update to the release version of v5.

v5 upgrade guide and release notes: https://rnfirebase.io/docs/v5.x.x/release-notes

https://github.com/invertase/react-native-firebase/blob/master/android/src/main/java/io/invertase/firebase/Utils.java#L174


Loving react-native-firebase and the support we provide? Please consider supporting us with any of the below:

@Salakar Hi :wave:,
When I send a firebase console notification to my application the application is crash and close.
I'm using
react-native-firebase": "^5.1.0

@Salakar Hi ,
When I send a firebase console notification to my application the application is crash and close.
I'm using
react-native-firebase": "^5.1.0

:wave: [Solved] :+1:

RN version 5.1.0

I did few of these steps:
:heavy_check_mark: Do check your libraries versions are same in android which you imported
:heavy_check_mark: You can check what versions of dependencies are resolved using gradlew app:dependencies on your android folder. All play-services libs should resolve to the same version, and all support libs should resolve to the same version.
:heavy_check_mark: If you are sending your notification from firebase console then don't forget to mention the channel.

:heavy_check_mark: AndroidManifext.xml
` package="com.rideshare.app">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 <uses-permission android:name="android.permission.WAKE_LOCK" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />

<application
  android:name=".MainApplication"
  android:label="@string/app_name"
  android:icon="@mipmap/ic_launcher"
  android:allowBackup="false"
  android:theme="@style/AppTheme">
  <activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
    android:launchMode="singleTop"
    android:windowSoftInputMode="adjustResize">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
  </activity>
  <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />


android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_stat_ic_notification" />

  <meta-data
     android:name="com.google.firebase.messaging.default_notification_color"
     android:resource="@color/colorAccent" />

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

  <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />

  <receiver android:name="io.invertase.firebase.notifications.RNFirebaseNotificationReceiver"/>
    <receiver 
    android:enabled="true" android:exported="true"  
    android:name="io.invertase.firebase.notifications.RNFirebaseNotificationsRebootReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
            <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>

</application>


`

:heavy_check_mark: build.gradle


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

buildscript {
    ext {
        buildToolsVersion = "28.0.2"
        minSdkVersion = 16
        compileSdkVersion = 27
        targetSdkVersion = 26
        supportLibVersion = "27.1.1"
    }
    repositories {
         google()
        jcenter()
             maven { url "https://maven.google.com" }
        maven { url "https://jitpack.io" }
        // Add repository
        maven {
           url 'https://maven.fabric.io/public'
        }



    }
    dependencies {

        classpath 'com.android.tools.build:gradle:3.1.4'
        //Firebase dependency 
        classpath 'com.google.gms:google-services:4.0.1'

        // Add dependency
        classpath 'io.fabric.tools:gradle:1.26.1'

        classpath 'com.google.firebase:firebase-plugins:1.1.5'

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

}

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

    }
}

  task wrapper(type: Wrapper) {
    gradleVersion = '4.6'
    distributionUrl = distributionUrl.replace("bin", "all")
}

:heavy_check_mark: app/build.gradle

````
apply plugin: "com.android.application"
apply plugin: 'io.fabric'

import com.android.build.OutputFile

/**

  • The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
  • and bundleReleaseJsAndAssets).
  • These basically call react-native bundle with the correct arguments during the Android build
  • cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
  • bundle directly from the development server. Below you can see all the possible configurations
  • and their defaults. If you decide to add a configuration block, make sure to add it before the
  • apply from: "../../node_modules/react-native/react.gradle" line.
    *
  • project.ext.react = [
  • // the name of the generated asset file containing your JS bundle
  • bundleAssetName: "index.android.bundle",
    *
  • // the entry file for bundle generation
  • entryFile: "index.android.js",
    *
  • // whether to bundle JS and assets in debug mode
  • bundleInDebug: false,
    *
  • // whether to bundle JS and assets in release mode
  • bundleInRelease: true,
    *
  • // whether to bundle JS and assets in another build variant (if configured).
  • // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
  • // The configuration property can be in the following formats
  • // 'bundleIn${productFlavor}${buildType}'
  • // 'bundleIn${buildType}'
  • // bundleInFreeDebug: true,
  • // bundleInPaidRelease: true,
  • // bundleInBeta: true,
    *
  • // whether to disable dev mode in custom build variants (by default only disabled in release)
  • // for example: to disable dev mode in the staging build type (if configured)
  • devDisabledInStaging: true,
  • // The configuration property can be in the following formats
  • // 'devDisabledIn${productFlavor}${buildType}'
  • // 'devDisabledIn${buildType}'
    *
  • // the root of your project, i.e. where "package.json" lives
  • root: "../../",
    *
  • // where to put the JS bundle asset in debug mode
  • jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
    *
  • // where to put the JS bundle asset in release mode
  • jsBundleDirRelease: "$buildDir/intermediates/assets/release",
    *
  • // where to put drawable resources / React Native assets, e.g. the ones you use via
  • // require('./image.png')), in debug mode
  • resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
    *
  • // where to put drawable resources / React Native assets, e.g. the ones you use via
  • // require('./image.png')), in release mode
  • resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
    *
  • // by default the gradle tasks are skipped if none of the JS files or assets change; this means
  • // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
  • // date; if you have any other folders that you want to ignore for performance reasons (gradle
  • // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
  • // for example, you might want to remove it from here.
  • inputExcludes: ["android/", "ios/"],
    *
  • // override which node gets called and with what additional arguments
  • nodeExecutableAndArgs: ["node"],
    *
  • // supply additional arguments to the packager
  • extraPackagerArgs: []
  • ]
    */

project.ext.react = [
entryFile: "index.js"
]

apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"

/**

  • Set this to true to create two separate APKs instead of one:

    • An APK that only works on ARM devices


    • An APK that only works on x86 devices

  • The advantage is the size of the APK is reduced by about 4MB.
  • Upload all the APKs to the Play Store and people will download
  • the correct one based on the CPU architecture of their device.
    */
    def enableSeparateBuildPerCPUArchitecture = false

/**

  • Run Proguard to shrink the Java bytecode in release builds.
    */
    def enableProguardInReleaseBuilds = false

android {
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion

lintOptions {
      abortOnError false
  }

defaultConfig {
    applicationId "com.rideshare.app"
    minSdkVersion rootProject.ext.minSdkVersion
    targetSdkVersion rootProject.ext.targetSdkVersion
    versionCode 1
    versionName "1.0"
    ndk {
        abiFilters "armeabi-v7a", "x86"
    }
}
splits {
    abi {
        reset()
        enable enableSeparateBuildPerCPUArchitecture
        universalApk false  // If true, also generate a universal APK
        include "armeabi-v7a", "x86"
    }
}
buildTypes {
    release {
        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:
        // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
        def versionCodes = ["armeabi-v7a":1, "x86":2]
        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
        }
    }
}

lintOptions {
    abortOnError false

}
}

dependencies {
compile project(':react-native-toasty')
//Firebase dependency
implementation project(':react-native-firebase')
implementation project(':react-native-image-picker')
// implementation project(':react-native-camera')
implementation project(':react-native-vector-icons')
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
implementation "com.facebook.react:react-native:+" // From node_modules

// Firebase dependencies
implementation "com.google.android.gms:play-services-base:16.0.1"
implementation "com.google.firebase:firebase-core:16.0.4"
//firebase auth
implementation "com.google.firebase:firebase-auth:16.0.5"
//firebase real-time database
implementation "com.google.firebase:firebase-database:16.0.4"
//firebase storage
implementation "com.google.firebase:firebase-storage:16.0.4"

// Push Notification RNFirebase
implementation "com.google.firebase:firebase-messaging:17.3.4"
implementation 'me.leolin:ShortcutBadger:1.1.21@aar'

// Crashlytics
implementation('com.crashlytics.sdk.android:crashlytics:2.9.5@aar') {
transitive = true
}

}

// 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'
}
//Firebase Plugin
apply plugin: 'com.google.gms.google-services'
com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true

```

i'm getting above original error upon receiving a push notification. RN 0.56.0 and firebase 5.1.1.

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.mydomain.myapp, PID: 9880
    java.lang.RuntimeException: Unable to start service io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService@a32d0cd with Intent { cmp=com.mydomain.myapp/io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService (has extras) }: java.lang.ClassCastException: android.app.Application cannot be cast to com.facebook.react.ReactApplication
        at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4079)
        at android.app.ActivityThread.access$2400(ActivityThread.java:221)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1897)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:158)
        at android.app.ActivityThread.main(ActivityThread.java:7225)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
     Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to com.facebook.react.ReactApplication
        at com.facebook.react.HeadlessJsTaskService.getReactNativeHost(HeadlessJsTaskService.java:169)
        at com.facebook.react.HeadlessJsTaskService.startTask(HeadlessJsTaskService.java:98)
        at com.facebook.react.HeadlessJsTaskService.onStartCommand(HeadlessJsTaskService.java:51)
        at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4062)
        at android.app.ActivityThread.access$2400(ActivityThread.java:221)聽
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1897)聽
        at android.os.Handler.dispatchMessage(Handler.java:102)聽
        at android.os.Looper.loop(Looper.java:158)聽
        at android.app.ActivityThread.main(ActivityThread.java:7225)聽
        at java.lang.reflect.Method.invoke(Native Method)聽
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)聽
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)聽

The plot thickens... Turns out my API FCM Server was sending notification payloads and data only payloads upon the same event, which is fine for iOS. But android... Well the notification is fine.

Its crashing on data only payloads.

Looking at this https://github.com/invertase/react-native-firebase/issues/906 but still having same problem no matter the config.

Update...
Having these issues on data only messages to android. Tried all the configs, same result as original error.

In the end i had to remove from android's app manifest https://rnfirebase.io/docs/v5.x.x/messaging/android#(Optional)-Background-Messages and abandon that feature of background data only messages

  <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />

Im having a similar issue, it seems to be linked to the notification icon

02-13 10:54:02.623  1208  3903 W System.err:    at java.lang.Thread.run(Thread.java:761)
02-13 10:54:02.636  6581  6607 V FA      : Connecting to remote service
02-13 10:54:02.643  6581  6607 D FA      : Connected to remote service
02-13 10:54:02.645  6581  6607 V FA      : Processing queued up service tasks: 1
02-13 10:54:02.648  1486  1486 W StatusBarIconView: No icon for slot com.testefcm/0x0
02-13 10:54:02.648  1486  1486 W StatusBar: removeNotification for unknown key: 0|com.testefcm|0|FCM-Notification:54665001|10395
02-13 10:54:02.658  6581  6581 E AndroidRuntime: FATAL EXCEPTION: main
02-13 10:54:02.658  6581  6581 E AndroidRuntime: Process: com.testefcm, PID: 6581
02-13 10:54:02.658  6581  6581 E AndroidRuntime: android.app.RemoteServiceException: Bad notification posted from package com.testefcm: Couldn't create icon: StatusBarIcon(icon=Icon(typ=RESOURCE pkg=com.testefcm id=0x7f0a0000) visible user=0 )
02-13 10:54:02.658  6581  6581 E AndroidRuntime:        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1743)
02-13 10:54:02.658  6581  6581 E AndroidRuntime:        at android.os.Handler.dispatchMessage(Handler.java:110)
02-13 10:54:02.658  6581  6581 E AndroidRuntime:        at android.os.Looper.loop(Looper.java:203)
02-13 10:54:02.658  6581  6581 E AndroidRuntime:        at android.app.ActivityThread.main(ActivityThread.java:6361)
02-13 10:54:02.658  6581  6581 E AndroidRuntime:        at java.lang.reflect.Method.invoke(Native Method)
02-13 10:54:02.658  6581  6581 E AndroidRuntime:        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
02-13 10:54:02.658  6581  6581 E AndroidRuntime:        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
02-13 10:54:02.666  1486  1486 W StatusBar: removeNotification for unknown key: 0|com.testefcm|0|FCM-Notification:54665001|10395
02-13 10:54:02.666  1208 22521 W ActivityManager:   Force finishing activity com.testefcm/.MainActivity`

i solved my crashing issue by adding:

<meta-data
      android:name="com.google.firebase.messaging.default_notification_icon"
      android:resource="@drawable/ic_small" />

to the AndroidManifest file inside <application></application>, and creating an png icon (18 x 18 px, ic_small.png) at the path app\src\main\res\drawable

android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@mipmap/ic_launcher" />

Was this page helpful?
0 / 5 - 0 ratings