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.63k stars 2.2k forks source link

🔥 [🐛] Android Repeatedly crashing when receiving messages in a background or quit state - complains of no WAKE_LOCK permissions. #7556

Closed WilliamHiggs closed 6 months ago

WilliamHiggs commented 8 months ago

Issue

(First off not a big Android Developer so if I've messed something up let me know!)

In the foreground the messages work fine but when I unfocus/close or full on quit the app and I receive a message, I get multiple crashes detailed below. Messages are sent from a server with HIGH prority, and seem to send fine looking at the FireBase console. Weirdly adding/removing setBackgroundMessageHandler from index.ts doesnt have any effect, it still crashes all the same.

Followed all the instructions listed here: https://rnfirebase.io/messaging/usage to add FireBase messaging to my Android App using Android Studio Giraffe | 2022.3.1 Patch 4. I've tested on a Samsung S23 on Android 13 AND A Nokia 7 Plus on Android 10.

I've tried other similar issue fixes. tried removing and adding in the services from AndroidManifest.xml. tried removing and adding the WAKE_LOCK permission. I've seen the issue of modern androids getting restrictive of waking devices because of battery life but it shouldnt be causing multiple crashes (enough to alert the user it is crashing). On a fairly old React-Native version (0.61) but unfortunetly locked into that version for now.

java.lang.RuntimeException: Unable to start receiver io.invertase.firebase.messaging.ReactNativeFirebaseMessagingReceiver: java.lang.SecurityException: Neither user 10336 nor current process has android.permission.WAKE_LOCK.
java.lang.RuntimeException: Unable to start service io.invertase.firebase.messaging.ReactNativeFirebaseMessagingHeadlessService@becabd with Intent { cmp=com.company.application/io.invertase.firebase.messaging.ReactNativeFirebaseMessagingHeadlessService (has extras) }: java.lang.SecurityException: Neither user 10336 nor current process has android.permission.WAKE_LOCK.

Full stack trace in Logcat is:

FATAL EXCEPTION: main
Process: com.company.application, PID: 22364
java.lang.RuntimeException: Unable to start service io.invertase.firebase.messaging.ReactNativeFirebaseMessagingHeadlessService@695b57d with Intent { cmp=com.company.application/io.invertase.firebase.messaging.ReactNativeFirebaseMessagingHeadlessService (has extras) }: java.lang.SecurityException: Neither user 10336 nor current process has android.permission.WAKE_LOCK.
    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:5286)
    at android.app.ActivityThread.-$$Nest$mhandleServiceArgs(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2531)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loopOnce(Looper.java:230)
    at android.os.Looper.loop(Looper.java:319)
    at android.app.ActivityThread.main(ActivityThread.java:8893)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:608)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1103)
Caused by: java.lang.SecurityException: Neither user 10336 nor current process has android.permission.WAKE_LOCK.
    at android.os.Parcel.createExceptionOrNull(Parcel.java:3069)
    at android.os.Parcel.createException(Parcel.java:3053)
    at android.os.Parcel.readException(Parcel.java:3036)
    at android.os.Parcel.readException(Parcel.java:2978)
    at android.os.IPowerManager$Stub$Proxy.acquireWakeLock(IPowerManager.java:1622)
    at android.os.PowerManager$WakeLock.acquireLocked(PowerManager.java:4667)
    at android.os.PowerManager$WakeLock.acquire(PowerManager.java:4632)
    at com.facebook.react.HeadlessJsTaskService.acquireWakeLockNow(HeadlessJsTaskService.java:77)
    at com.facebook.react.HeadlessJsTaskService.startTask(HeadlessJsTaskService.java:95)
    at com.facebook.react.HeadlessJsTaskService.onStartCommand(HeadlessJsTaskService.java:48)
    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:5268)
    at android.app.ActivityThread.-$$Nest$mhandleServiceArgs(Unknown Source:0) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2531) 
    at android.os.Handler.dispatchMessage(Handler.java:106) 
    at android.os.Looper.loopOnce(Looper.java:230) 
    at android.os.Looper.loop(Looper.java:319) 
    at android.app.ActivityThread.main(ActivityThread.java:8893) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:608) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1103) 
Caused by: android.os.RemoteException: Remote stack trace:
    at android.app.ContextImpl.enforce(ContextImpl.java:2418)
    at android.app.ContextImpl.enforceCallingOrSelfPermission(ContextImpl.java:2446)
    at com.android.server.power.PowerManagerService$BinderService.acquireWakeLock(PowerManagerService.java:8522)
    at android.os.IPowerManager$Stub.onTransact(IPowerManager.java:758)
    at android.os.Binder.execTransactInternal(Binder.java:1375)

Project Files

Javascript

Click To Expand

#### `package.json`: ```json { "name": "Application", "version": "0.0.1", "private": true, "scripts": { "android": "react-native run-android", "ios": "react-native run-ios", "start": "react-native start", "test": "jest", "lint": "eslint .", "postinstall": "patch-package" }, "dependencies": { "@fortawesome/fontawesome-svg-core": "^1.2.27", "@fortawesome/free-solid-svg-icons": "^5.12.1", "@fortawesome/react-native-fontawesome": "^0.2.2", "@pusher/pusher-websocket-react-native": "^1.2.2", "@react-native-community/async-storage": "^1.8.0", "@react-native-community/datetimepicker": "^3.0.3", "@react-native-community/masked-view": "^0.1.6", "@react-native-community/netinfo": "^6.0.0", "@react-native-community/push-notification-ios": "^1.1.1", "@react-native-community/toolbar-android": "^0.2.1", "@react-native-firebase/app": "18.2.0", "@react-native-firebase/messaging": "18.2.0", "@types/eventemitter3": "^2.0.2", "@types/react": "^16.9.20", "@types/react-dom": "^16.9.5", "@types/react-native-linear-gradient": "^2.4.0", "axios": "^0.19.2", "moment": "^2.24.0", "patch-package": "^6.4.7", "react": "16.9.0", "react-native": "0.61.5", "react-native-animatable": "^1.3.3", "react-native-button": "^3.0.0", "react-native-camera": "^3.23.1", "react-native-dash": "^0.0.11", "react-native-device-info": "^5.5.3", "react-native-easy-grid": "^0.2.2", "react-native-elements": "^1.2.7", "react-native-fast-image": "^8.3.4", "react-native-gesture-handler": "^1.6.0", "react-native-interactable": "^2.0.1", "react-native-keyboard-aware-scroll-view": "^0.9.1", "react-native-material-dropdown": "^0.11.1", "react-native-modal": "^11.5.4", "react-native-modal-datetime-picker": "^9.0.0", "react-native-permissions": "^2.1.5", "react-native-picker-select": "^7.0.0", "react-native-qr-generator": "^1.0.4", "react-native-reanimated": "1.13.2", "react-native-render-html": "6.1.0", "react-native-safe-area-context": "^0.7.3", "react-native-safe-area-view": "^1.0.0", "react-native-screens": "^2.0.0-beta.6", "react-native-simple-store": "^2.0.2", "react-native-simple-toast": "^1.0.0", "react-native-svg": "12.1.0", "react-native-swipe-list-view": "^3.0.0-rc1", "react-native-uuid": "^1.4.9", "react-native-vector-icons": "6.7.0", "react-navigation": "^4.1.1", "react-navigation-stack": "^2.1.1", "rn-bottom-drawer": "^1.4.3", "rn-fetch-blob": "^0.12.0" }, "devDependencies": { "@babel/core": "7.16.5", "@babel/preset-flow": "7.16.5", "@babel/runtime": "7.16.5", "@react-native-community/eslint-config": "^0.0.5", "babel-jest": "^24.9.0", "eslint": "^6.5.1", "jest": "^24.9.0", "metro-react-native-babel-preset": "^0.56.0", "react-test-renderer": "16.9.0" }, "resolutions": { "@babel/traverse": "7.16.5", "@types/react": "17.0.2", "@types/react-dom": "17.0.2" }, "jest": { "preset": "react-native" } } ``` #### `firebase.json` for react-native-firebase v6: ```json # N/A ```

iOS

Click To Expand

#### `ios/Podfile`: - [x] I'm not using Pods - [] 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? No - [ ] my application is an AndroidX application? - [x] 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 = "30.0.3" minSdkVersion = 21 compileSdkVersion = 33 targetSdkVersion = 33 excludeAppGlideModule = true } repositories { google() jcenter() } dependencies { classpath('com.android.tools.build:gradle:4.2.2') classpath 'com.google.gms:google-services:4.3.15' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } def REACT_NATIVE_VERSION = new File(['node', '--print',"JSON.parse(require('fs').readFileSync(require.resolve('react-native/package.json'), 'utf-8')).version"].execute(null, rootDir).text.trim()) 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") } google() jcenter() maven { url 'https://jitpack.io' } maven { url "https://maven.google.com" } } configurations.all { resolutionStrategy { force "com.facebook.react:react-native:" + REACT_NATIVE_VERSION } } } ``` #### `android/app/build.gradle`: ```groovy apply plugin: "com.android.application" apply plugin: 'com.google.gms.google-services' 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.ts", enableHermes: false, // clean and rebuild if changing ] apply from: "../../node_modules/react-native/react.gradle" project.ext.vectoricons = [ iconFontNames: [ 'FontAwesome.ttf', ] // Specify font files ] apply from: file("../../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 /** * The preferred build flavor of JavaScriptCore. * * For example, to use the international variant, you can use: * `def jscFlavor = 'org.webkit:android-jsc-intl:+'` * * The 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 jscFlavor = 'org.webkit:android-jsc:+' /** * Whether to enable the Hermes VM. * * This should be set on project.ext.react and mirrored here. If it is not set * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode * and the benefits of using Hermes will therefore be sharply reduced. */ 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.company.application" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 2 versionName "2.0.0" missingDimensionStrategy 'react-native-camera', 'general', 'mlkit' 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 { 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 } } } lintOptions { checkReleaseBuilds false } } allprojects { repositories { exclusiveContent { // We get React Native's Android binaries exclusively through npm, // from a local Maven repo inside node_modules/react-native/. // (The use of exclusiveContent prevents looking elsewhere like Maven Central // and potentially getting a wrong version.) filter { includeGroup "com.facebook.react" } forRepository { maven { url "$rootDir/../node_modules/react-native/android" } } } // ... } } dependencies { implementation project(':react-native-vector-icons') implementation fileTree(dir: "libs", include: ["*.jar"]) implementation "com.facebook.react:react-native:+" // From node_modules implementation 'com.facebook.fresco:fresco:2.0.0' implementation 'com.facebook.fresco:animated-gif:2.0.0' // Import the Firebase BoM implementation platform('com.google.firebase:firebase-bom:32.7.0') // When using the BoM, don't specify versions in Firebase dependencies implementation 'com.google.firebase:firebase-analytics' implementation 'com.google.firebase:firebase-messaging' 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) ``` #### `android/settings.gradle`: ```groovy rootProject.name = 'Application' include ':react-native-vector-icons' project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android') apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings) include ':app' ``` #### `MainApplication.java`: ```java package com.company.application; import android.app.Application; import android.content.Context; import com.facebook.react.PackageList; import com.facebook.react.ReactApplication; import com.oblador.vectoricons.VectorIconsPackage; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.soloader.SoLoader; import java.lang.reflect.InvocationTargetException; import io.invertase.firebase.messaging.ReactNativeFirebaseMessagingPackage; 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() { @SuppressWarnings("UnnecessaryLocalVariable") List packages = new PackageList(this).getPackages(); // Packages that cannot be autolinked yet can be added manually here, for example: // packages.add(new MyReactNativePackage()); 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); initializeFlipper(this); // Remove this line if you don't want Flipper enabled } /** * Loads Flipper in React Native templates. * * @param context */ private static void initializeFlipper(Context context) { if (BuildConfig.DEBUG) { try { /* We use reflection here to pick up the class that initializes Flipper, since Flipper library is not available in release mode */ Class aClass = Class.forName("com.facebook.flipper.ReactNativeFlipper"); aClass.getMethod("initializeFlipper", Context.class).invoke(null, context); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } } ``` #### `AndroidManifest.xml`: ```xml ```


Environment

Click To Expand

**`react-native info` output:** ``` System: OS: macOS 13.5.1 CPU: (10) arm64 Apple M1 Max Memory: 82.64 MB / 32.00 GB Shell: 5.9 - /bin/zsh Binaries: Node: 16.13.1 - ~/.nvm/versions/node/v16.13.1/bin/node Yarn: 1.22.4 - /usr/local/bin/yarn npm: 8.1.2 - ~/.nvm/versions/node/v16.13.1/bin/npm Watchman: 2023.12.04.00 - /usr/local/bin/watchman SDKs: iOS SDK: Platforms: DriverKit 23.0, iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0 Android SDK: API Levels: 28, 29, 30, 31, 32, 33 Build Tools: 28.0.3, 29.0.2, 30.0.2, 30.0.3, 33.0.0 System Images: android-31 | Google Play ARM 64 v8a, android-33 | Google APIs ARM 64 v8a IDEs: Android Studio: 2022.3 AI-223.8836.35.2231.11090377 Xcode: 15.0/15A240d - /usr/bin/xcodebuild npmPackages: react: 16.9.0 => 16.9.0 react-native: 0.61.5 => 0.61.5 ``` - **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:** - `Using BoM 32.7.0, not using the react-native-firebase package.` - **`Firebase` module(s) you're using that has the issue:** - `messaging` - **Are you using `TypeScript`?** - `Y - unknown version but can advise on request`


mikehardy commented 7 months ago

Does this still happen if you use current releases? They bring in new underlying firebase-android-sdk which may solve this

    "@react-native-firebase/app": "18.2.0",
    "@react-native-firebase/messaging": "18.2.0",

Very strange that the error would happen despite this in your AndroidManifest.xml

    <uses-permission
        android:name="android.permission.WAKE_LOCK"
        tools:node="replace" />

...I don't understand that a bit. I'd try a brand-new react-native app with a clean integration on messaging as a throw-away example and see if it still happens.

I maintain a build-demo script that you might be able to use as a starter and then just delete all the modules you don't care about https://github.com/mikehardy/rnfbdemo/blob/main/make-demo.sh

mikehardy commented 7 months ago

To be slightly more clear - without a reproduction this likely won't receive more attention. Native messaging is one of the main reasons people use react-native-firebase vs just using firebase-js-sdk, and Android 13 has been out quite a while, including on my personal phones with my production app, and it does not crash. No one else is reproducing this

github-actions[bot] commented 6 months ago

Hello 👋, to help manage issues we automatically close stale issues.

This issue has been automatically marked as stale because it has not had activity for quite some time.Has this issue been fixed, or does it still require attention?

This issue will be closed in 15 days if no further activity occurs.

Thank you for your contributions.