invertase / react-native-firebase

🔥 A well-tested feature-rich modular Firebase implementation for React Native. Supports both iOS & Android platforms for all Firebase services.
https://rnfirebase.io
Other
11.54k stars 2.19k forks source link

Android crash on notification when app closed, working in background or foreground [iOS works] #3387

Closed peter1a closed 4 years ago

peter1a commented 4 years ago

Issue

04-02 13:52:31.084 28418 28418 D SoLoader: Preparing SO source: com.facebook.soloader.ApkSoSource[root = /data/data/com.internet1a.mojeure/lib-main flags = 1] 04-02 13:52:31.085 28418 28418 V fb-UnpackingSoSource: locked dso store /data/user/0/com.internet1a.mojeure/lib-main 04-02 13:52:31.087 28418 28418 I fb-UnpackingSoSource: dso store is up-to-date: /data/user/0/com.internet1a.mojeure/lib-main 04-02 13:52:31.087 28418 28418 V fb-UnpackingSoSource: releasing dso store lock for /data/user/0/com.internet1a.mojeure/lib-main 04-02 13:52:31.118 28418 28434 E AndroidRuntime: Process: com.internet1a.mojeure, PID: 28418 04-02 13:52:31.118 28418 28434 E AndroidRuntime: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.internet1a.mojeure. Make sure to call FirebaseApp.initializeApp(Context) first. 04-02 13:52:31.123 3648 13396 W ActivityManager: crash : com.internet1a.mojeure,0

Push notification works in iOS (release & development), works on Android (foreground / background), doesn't work if app is closed, i get error: X has stopped. I provide log from adb logcat.


Project Files

Javascript

JavaScript code

pushNotifications() {
        // initalize app before token registration
        firebase.initializeApp(Config.FCM_SETTINGS);

        if(firebase) {
            // get notification in foreground and token registration
            firebase.messaging().hasPermission().then(enabled => {
                if (enabled) {
                } else {
                    firebase.messaging().requestPermission().then(() => {
                        // User has authorised
                    }).catch(error => {
                        // User has rejected permissions
                    });
                }
            });

            // get token for registration
            firebase.messaging().getToken().then(fcmToken => {
                if (fcmToken) {
                    this.setState({
                        Token: fcmToken
                    });
                }
            });

            // get push notification while app is open
            firebase.notifications().onNotification((output) => {
                alert(JSON.stringify(output._data));
            });
        }
    }
Click To Expand

#### `package.json`: ```json react-native-firebase": "^5.6.0", "native-base": "^2.12.1", "query-string": "^6.4.2", "react": "16.8.3", "react-native": "^0.59.6", "react-native-a-beep": "^1.0.1", "react-native-ble-manager": "^6.6.2", "react-native-camera": "^2.6.0", "react-native-device-info": "^1.5.0", "react-native-gesture-handler": "^1.1.0", "react-native-modal-datetime-picker": "^6.1.0", "react-native-network-info": "^5.2.1", "react-native-nfc-manager": "^1.2.2", "react-native-qrcode-scanner": "^1.1.2", "react-native-splash-screen": "^3.2.0", "react-native-vector-icons": "^6.4.2", "react-navigation": "^3.6.1" #### `AndroidManifest.xml`: ``` #### `firebase.json` for react-native-firebase v6: ```json # N/A ```

iOS

Click To Expand

#### `ios/Podfile`: - [ ] I'm not using Pods - [x] I'm using Pods and my Podfile looks like: ```ruby # N/A ``` #### `AppDelegate.m`: ```objc // N/A ```


Android

Click To Expand

#### Have you converted to AndroidX? - [ ] my application is an AndroidX application? - [ ] I am using `android/gradle.settings` `jetifier=true` for Android compatibility? - [ ] I am using the NPM package `jetifier` for react-native compatibility? #### `android/build.gradle`: ```groovy // 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" googlePlayServicesVersion = "15.0.1" } repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.3.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() google() jcenter() maven { // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm url "$rootDir/../node_modules/react-native/android" } } } apply plugin: 'com.google.gms.google-services' ``` #### `android/app/build.gradle`: ```groovy 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", * * // 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" /** * 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 compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } defaultConfig { applicationId "com.internet1a.mojeure" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 56 versionName "1.2.7" missingDimensionStrategy 'react-native-camera', 'general' } signingConfigs { release { if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) { storeFile file(MYAPP_RELEASE_STORE_FILE) storePassword MYAPP_RELEASE_STORE_PASSWORD keyAlias MYAPP_RELEASE_KEY_ALIAS keyPassword MYAPP_RELEASE_KEY_PASSWORD } } } splits { abi { reset() enable enableSeparateBuildPerCPUArchitecture universalApk false // If true, also generate a universal APK include "armeabi-v7a", "x86", "arm64-v8a", "x86_64" } } buildTypes { release { minifyEnabled enableProguardInReleaseBuilds proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" signingConfig signingConfigs.release } } // 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, "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 "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 project(':react-native-a-beep') implementation project(':react-native-camera') implementation project(':react-native-device-info') implementation project(':react-native-nfc-manager') implementation project(':react-native-splash-screen') implementation project(':react-native-vector-icons') implementation project(':react-native-gesture-handler') implementation project(':react-native-ble-manager') implementation project(':react-native-network-info') implementation fileTree(dir: "libs", include: ["*.jar"]) implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}" implementation "com.facebook.react:react-native:+" // From node_modules } // 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' } com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true ``` #### `android/settings.gradle`: ```groovy rootProject.name = 'app_mojeure' include ':react-native-a-beep' project(':react-native-a-beep').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-a-beep/android') include ':react-native-camera' project(':react-native-camera').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-camera/android') include ':react-native-device-info' project(':react-native-device-info').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-device-info/android') include ':react-native-nfc-manager' project(':react-native-nfc-manager').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-nfc-manager/android') include ':react-native-splash-screen' project(':react-native-splash-screen').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-splash-screen/android') include ':react-native-vector-icons' project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android') include ':react-native-gesture-handler' project(':react-native-gesture-handler').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-gesture-handler/android') include ':react-native-ble-manager' project(':react-native-ble-manager').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-ble-manager/android') include ':react-native-network-info' project(':react-native-network-info').projectDir = new File(settingsDir, '../node_modules/react-native-network-info/android') include ':react-native-firebase' project(':react-native-firebase').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-firebase/android') include ':app' ``` #### `MainApplication.java`: ```java package com.internet1a.mojeure; import android.app.Application; import com.facebook.react.ReactApplication; import com.oblador.vectoricons.VectorIconsPackage; import com.swmansion.gesturehandler.react.RNGestureHandlerPackage; import it.innove.BleManagerPackage; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import com.facebook.soloader.SoLoader; import org.devio.rn.splashscreen.SplashScreenReactPackage; import community.revteltech.nfc.NfcManagerPackage; import com.learnium.RNDeviceInfo.RNDeviceInfo; import org.reactnative.camera.RNCameraPackage; import com.reactlibrary.RNReactNativeABeepPackage; import com.pusherman.networkinfo.RNNetworkInfoPackage; import io.invertase.firebase.RNFirebasePackage; import io.invertase.firebase.messaging.RNFirebaseMessagingPackage; import io.invertase.firebase.notifications.RNFirebaseNotificationsPackage; import java.util.Arrays; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List getPackages() { return Arrays.asList( new MainReactPackage(), new VectorIconsPackage(), new RNGestureHandlerPackage(), new BleManagerPackage(), new SplashScreenReactPackage(), new NfcManagerPackage(), new RNDeviceInfo(), new RNCameraPackage(), new RNReactNativeABeepPackage(), new RNNetworkInfoPackage(), new RNFirebasePackage(), new RNFirebaseMessagingPackage(), new RNFirebaseNotificationsPackage() ); } @Override protected String getJSMainModuleName() { return "index"; } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); SoLoader.init(this, /* native exopackage */ false); } } ``` ```xml ```


Environment

Click To Expand

**`react-native info` output:** ``` OUTPUT GOES HERE ``` - **Platform that you're experiencing the issue on**: - [ ] iOS - [x] Android - [ ] **iOS** but have not tested behavior on Android - [ ] **Android** but have not tested behavior on iOS - [ ] Both - **`react-native-firebase` version you're using that has this issue:** - `e.g. 5.4.3` - **`Firebase` module(s) you're using that has the issue:** - `e.g. Instance ID` - **Are you using `TypeScript`?** - `Y/N` & `VERSION`


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]

mikehardy commented 4 years ago

5.4.3 is too old for support, you should upgrade at least to 5.6.0 if you must stay on v5, and you should update to current firebase bom dependencies (25.2.0 right now)

peter1a commented 4 years ago

5.4.3 is too old for support, you should upgrade at least to 5.6.0 if you must stay on v5, and you should update to current firebase bom dependencies (25.2.0 right now)

Current version of firebase is 5.5.6. I can try to install 5.6.0 if will work. Any other ideas what should I change?

mikehardy commented 4 years ago

Then you haven't filled out the template, that was the default value. Please completely fill out the template

peter1a commented 4 years ago

I have updated firebase to 5.6.0, no changes, still same error.

mikehardy commented 4 years ago

Strange. Normally I'd say this is an auto-linking failure but you're still on RN59 and things seem right.

I have seen a nearly infinite amount of project-integration failures, so rather than look through them all I instead demo how to do them here: https://github.com/mikehardy/rnfbdemo/blob/master/make-demo-rn59.sh but even that doesn't seem to really apply here as you mention it works except when app closed.

I have low hopes for this one but I notice you aren't on react-native 0.59-latest, why not try 0.59.10? They may have fixed something with regard to app startup order there?

peter1a commented 4 years ago

Fixed, probem was not having apply plugin: 'com.google.gms.google-services' in app/build.gradle, therefore app can't make initalization in background or when it's closed.