React-native-firebase: Error: You attempted to use a firebase module that's not installed on your Android project by calling firebase.messaging().

Created on 15 Jul 2019  路  17Comments  路  Source: invertase/react-native-firebase

Issue



Describe your issue here

I'm using RN 0.60.0 and RNFirebase 5.5.5. I wanted to add push notifications using firebase. I followed the docs and added all the required things. I'm getting this issue. Error: You attempted to use a firebase module that's not installed on your Android project by calling firebase.messaging(). I am facing this issue in android in the real device.


Project Files






iOS

Click To Expand

#### `ios/Podfile`: - [ ] I'm not using Pods - [x] I'm using Pods and my Podfile looks like:

# N/A
#### `AppDelegate.m`:
// N/A


Android

Click To Expand

#### Have you converted to AndroidX? - [x] my application is an AndroidX application? - [x] I am using `android/gradle.settings` `jetifier=true` for Android compatibility? - [x] I am using the NPM package `jetifier` for react-native compatibility? #### `android/build.gradle`:

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

buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
        supportLibVersion = "28.0.0"
    }
    repositories {
        google()
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:3.4.1")
        classpath 'com.google.gms:google-services:4.2.0'

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

allprojects {
    repositories {
        mavenLocal()
        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://jitpack.io" }
        maven { url "https://maven.google.com" }

        google()
        jcenter()
    }
}

#### `android/app/build.gradle`:
apply plugin: "com.android.application"

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",
 *
 *   // https://facebook.github.io/react-native/docs/performance#enable-the-ram-format
 *   bundleCommand: "ram-bundle",
 *
 *   // 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"

project.ext.vectoricons = [
    iconFontNames: [ 'FontAwesome.ttf' ] // Name of the font files you want to copy
]
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

/**
 * Use international variant JavaScriptCore
 * International variant includes ICU i18n library and necessary data allowing to use
 * e.g. Date.toLocaleString and String.localeCompare that give correct results
 * when using with locales other than en-US.
 * Note that this variant is about 6MiB larger per architecture than default.
 */
def useIntlJsc = false

android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.restart"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
        vectorDrawables.useSupportLibrary = 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 {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://facebook.github.io/react-native/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 project(':react-native-firebase')
    implementation project(':react-native-push-notification')
    implementation project(':react-native-fbsdk')
    implementation project(':react-native-image-crop-picker')
    implementation project(':react-native-gesture-handler')
    implementation project(':react-native-linear-gradient')
    implementation 'com.facebook.android:facebook-android-sdk:[5,6)'
    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:18.0.0"
    // implementation 'me.leolin:ShortcutBadger:1.1.21@aar'

    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.facebook.react:react-native:+"  // From node_modules

    // JSC from node_modules
    if (useIntlJsc) {
        implementation 'org.webkit:android-jsc-intl:+'
    } else {
        implementation 'org.webkit:android-jsc:+'
    }
}

// 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'
#### `android/settings.gradle`:
rootProject.name = 'restart'
include ':react-native-firebase'
project(':react-native-firebase').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-firebase/android')
include ':react-native-push-notification'
project(':react-native-push-notification').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-push-notification/android')
include ':react-native-fbsdk'
project(':react-native-fbsdk').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-fbsdk/android')
include ':react-native-image-crop-picker'
project(':react-native-image-crop-picker').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-image-crop-picker/android')
include ':react-native-gesture-handler'
project(':react-native-gesture-handler').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-gesture-handler/android')
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'

include ':react-native-linear-gradient'
project(':react-native-linear-gradient').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-linear-gradient/android')

include ':react-native-fbsdk'
project(':react-native-fbsdk').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-fbsdk/android')

include ':react-native-push-notification'
project(':react-native-push-notification').projectDir = file('../node_modules/react-native-push-notification/android')
#### `MainApplication.java`:
package com.restart;

import android.app.Application;

import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import io.invertase.firebase.RNFirebasePackage;
import com.dieam.reactnativepushnotification.ReactNativePushNotificationPackage;
import com.facebook.reactnative.androidsdk.FBSDKPackage;
import com.reactnative.ivpusic.imagepicker.PickerPackage;
import com.swmansion.gesturehandler.react.RNGestureHandlerPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import com.BV.LinearGradient.LinearGradientPackage;
import java.util.List;
import io.invertase.firebase.messaging.RNFirebaseMessagingPackage;
import io.invertase.firebase.notifications.RNFirebaseNotificationsPackage;


public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    public boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      @SuppressWarnings("UnnecessaryLocalVariable")
      List<ReactPackage> packages = new PackageList(this).getPackages();
      // Packages that cannot be autolinked yet can be added manually here, for example:
      // packages.add(new MyReactNativePackage());
      new LinearGradientPackage();
      new FBSDKPackage();
      new RNFirebasePackage();
      new RNFirebaseMessagingPackage();
      // new RNFirebaseNotificationsPackage();
      // new RNCameraPackage();
      return packages;
    }

    @Override
    protected String getJSMainModuleName() {
      return "index";
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
  }
}

#### `AndroidManifest.xml`:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.restart">

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

  <application android:name=".MainApplication" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:allowBackup="false" android:theme="@style/AppTheme">
    <activity android:name=".MainActivity" android:label="@string/app_name" android:configChanges="keyboard|keyboardHidden|orientation|screenSize" android:windowSoftInputMode="adjustResize" android:launchMode="singleTop">
      <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" />
    <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
    <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 resource name to your App's accent color - or any other color you want -->
    <meta-data android:name="com.dieam.reactnativepushnotification.notification_color" android:resource="@android:color/white"/>
    <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" />
      </intent-filter>
    </receiver>
    <service android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationRegistrationService"/>
    <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
      <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
      </intent-filter>
    </service>
    <!-- <meta-data 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" /> -->
  </application>

</manifest>


Environment

Click To Expand

**`react-native info` output:**

OS: macOS High Sierra 10.13.6
    CPU: (4) x64 Intel(R) Core(TM) i5-7360U CPU @ 2.30GHz
    Memory: 142.00 MB / 8.00 GB
    Shell: 3.2.57 - /bin/bash
  Binaries:
    Node: 10.15.0 - /usr/local/bin/node
    Yarn: 1.13.0 - /usr/local/bin/yarn
    npm: 6.8.0 - /usr/local/bin/npm
    Watchman: 4.9.0 - /usr/local/bin/watchman
  SDKs:
    iOS SDK:
      Platforms: iOS 12.1, macOS 10.14, tvOS 12.1, watchOS 5.1
    Android SDK:
      API Levels: 27, 28, 29
      Build Tools: 27.0.3, 28.0.3, 29.0.0
      System Images: android-27 | Intel x86 Atom_64, android-28 | Google APIs Intel x86 Atom, android-28 | Google Play Intel x86 Atom
  IDEs:
    Android Studio: 3.4 AI-183.6156.11.34.5522156
    Xcode: 10.1/10B61 - /usr/bin/xcodebuild
  npmPackages:
    react: 16.8.6 => 16.8.6 
    react-native: 0.60.0 => 0.60.0 
  npmGlobalPackages:
    react-native-cli: 2.0.1
 OUTPUT GOES HERE

Possible Unhandled Promise Rejection (id: 0):
Error: You attempted to use a firebase module that's not installed on your Android project by calling firebase.messaging().

Ensure you have:

1) Installed the required Firebase Android SDK dependency 'com.google.firebase:firebase-messaging' in your 'android/app/build.gradle' file.

2) Imported the 'io.invertase.firebase.messaging.RNFirebaseMessagingPackage' module in your 'MainApplication.java' file.

3) Added the 'new RNFirebaseMessagingPackage()' line inside of the RN 'getPackages()' method list.

- **Platform that you're experiencing the issue on**: - [ ] iOS - [x] Android - [ ] **iOS** but have not tested behavior on Android - [x] **Android** but have not tested behavior on iOS - [ ] Both - **`react-native-firebase` version you're using that has this issue:** - `e.g. 5.5.5` - **`Firebase` module(s) you're using that has the issue:** - `Messaging and Notifications` - **Are you using `TypeScript`?** - `N`




Think react-native-firebase is great? Please consider supporting all of the project maintainers and contributors by donating via our Open Collective where all contributors can submit expenses. [Learn More]

Most helpful comment

If you check the comments in getPackages() function you shouldn't add the packages the old way, you should add them to PackageList generated by the cli.

instead of:

@Override
    protected List<ReactPackage> getPackages() {
      @SuppressWarnings("UnnecessaryLocalVariable")
      List<ReactPackage> packages = new PackageList(this).getPackages();
      // Packages that cannot be autolinked yet can be added manually here, for example:
      // packages.add(new MyReactNativePackage());
      new LinearGradientPackage();
      new FBSDKPackage();
      new RNFirebasePackage();
      new RNFirebaseMessagingPackage();
      // new RNFirebaseNotificationsPackage();
      // new RNCameraPackage();
      return packages;
    }

you should do:

@Override
    protected List<ReactPackage> getPackages() {
      @SuppressWarnings("UnnecessaryLocalVariable")
      List<ReactPackage> packages = new PackageList(this).getPackages();
      // Packages that cannot be autolinked yet can be added manually here, for example:
      // packages.add(new MyReactNativePackage());
      packages.add(new LinearGradientPackage());
      packages.add(new FBSDKPackage());
      packages.add(new RNFirebaseMessagingPackage());
      return packages;
    }

Notice that RNFirebasePackage() is not added in this function, because if your project was autolinked, this package was already added in PackagesList file. if you get a message like duplicate package name... or something, then probably this package was already autolinked and doesn't have to be manually added.

All 17 comments

If you check the comments in getPackages() function you shouldn't add the packages the old way, you should add them to PackageList generated by the cli.

instead of:

@Override
    protected List<ReactPackage> getPackages() {
      @SuppressWarnings("UnnecessaryLocalVariable")
      List<ReactPackage> packages = new PackageList(this).getPackages();
      // Packages that cannot be autolinked yet can be added manually here, for example:
      // packages.add(new MyReactNativePackage());
      new LinearGradientPackage();
      new FBSDKPackage();
      new RNFirebasePackage();
      new RNFirebaseMessagingPackage();
      // new RNFirebaseNotificationsPackage();
      // new RNCameraPackage();
      return packages;
    }

you should do:

@Override
    protected List<ReactPackage> getPackages() {
      @SuppressWarnings("UnnecessaryLocalVariable")
      List<ReactPackage> packages = new PackageList(this).getPackages();
      // Packages that cannot be autolinked yet can be added manually here, for example:
      // packages.add(new MyReactNativePackage());
      packages.add(new LinearGradientPackage());
      packages.add(new FBSDKPackage());
      packages.add(new RNFirebaseMessagingPackage());
      return packages;
    }

Notice that RNFirebasePackage() is not added in this function, because if your project was autolinked, this package was already added in PackagesList file. if you get a message like duplicate package name... or something, then probably this package was already autolinked and doesn't have to be manually added.

Thanks. It's working.

@hopewise this is an issue closed months ago, and you post no information required to troubleshoot, how would you help if it was you attempting to troubleshoot? 馃 Please open a new issue following the template if this persists, but there is likely something wrong in your project setup. I definitely use https://rnfirebase.io/docs/v5.x.x/messaging/receiving-messages#3)-Register-the-background-handler and were I too upgrade to v6 I would do it like so https://github.com/invertase/react-native-firebase/pull/2806#issuecomment-549073274

Thanks @mikehardy , will create new issue, however, I've checked your doc link, it seems I am still using old listener, as there is no setBackgroundMessageHandler mentioned in the 5.x.x

@hopewise I don't believe you need a new issue then, you just need to examine the comments on that docs PR

=> mainAppliction.java

add these line

import io.invertase.firebase.messaging.RNFirebaseMessagingPackage; // <-- Add this line

and add package

packages.add(new RNFirebaseMessagingPackage());

Thanks @jitendra-Tech, @mikehardy following 5.x.x docs nailed it 馃憤

@hopewise Excellent! Good luck

@jitendra-Tech I'm importing that package and also adding it the same way you suggest, but from time to time, i'm getting these Sentry error logs saying:

Error: You attempted to use a firebase module that's not installed on your Android project by calling firebase.notifications().

Ensure you have:

1) Installed the required Firebase Android SDK dependency 'com.google.firebase:firebase-notifications' in ...
    at initialiseNativeModule(index.android.bundle:931)
    at t(index.android.bundle:932)
    at h(index.android.bundle:1004)
    at (index.android.bundle:924)
    at (index.android.bundle:924)
...
(45 additional frame(s) were not displayed)

What could be the reason of this?

Getting this error on iOS. Has anyone solved it?

@pvanny1124 always a local project integration issue. I'll assume at this point you're using react-native-firebase v6+ and react-native 0.60+ (if not, you're effectively out of support) - so you can see a working demo that shows it here: https://github.com/mikehardy/rnfbdemo/blob/master/make-demo-v6.sh (not 100% messaging is in there but the basic repetition of how to install the modules is all shown, and you can extend it easily by adding messaging to show it works). Might be just as easy as remembering to do cd ios && pod install

Hey Mike, thanks a lot for the reply. I'm effectively using RN 0.60+ and RNFv6.7.1. I just migrated from using RN 0.59 and RNFv5.2.1.

I'm having issues trying to find out how to replace firebase.notifications() in the following sample code:

 this.notificationDisplayedListener = firebase.notifications().onNotificationDisplayed(() => {});
      this.notificationListener = firebase.notifications().onNotification(async notification => {
        const localNotification = new firebase.notifications.Notification()
          .setNotificationId(notification.notificationId)
          .setTitle(notification.title)
          .setSubtitle(notification.subtitle)
          .setBody(notification.body)
          .setData(notification.data)
          .android.setSmallIcon('ic_stat_notification')
          .android.setChannelId('test-channel')
          .android.setPriority(firebase.notifications.Android.Priority.High)
          .setSound('default');

        firebase
          .notifications()
          .displayNotification(localNotification)
          .catch(() => {});
      });

I appreciate the help!

local notifications APIs are no longer in react-native-firebase
you need to integrate a local notifications package, one of these can work:
notifee
react-native-notifications
react-native-push-notifications

firebase will handle the cloud messaging and the notifications package will handle notifications

Awesome, thanks @mikehardy. I'll try them out!

io.invertase.firebase.messaging.RNFirebaseMessagingPackage

mainAppliction.java

Where is this mainApplication.java in my project i don't find it

Was this page helpful?
0 / 5 - 0 ratings