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.64k stars 2.21k forks source link

setBackgroundMessageHandler not working with multiple native Activities #5219

Closed NIyerAD closed 3 years ago

NIyerAD commented 3 years ago

Issue

Hi everyone!

I have a somewhat unique (i think) issue here. I'm currently using FCM in order to receive notifications in my softphone app in all states (foreground/background/killed) . My scenario is as follows:

When my app is killed and my device is locked, I receive an inbound call notification that launches a full screen intent activity with answer and reject buttons that is designed to show over the lock screen. However, if the caller decides to cancel their call, the server sends a 'cancel' push message that should be picked up by the messaging().setBackgroundMessageHandler() which will cancel the notification and destroy the native activity. The problem is that the background handler won't trigger because react-native-firebase thinks that the app is now in the foreground as the incoming call activity has been shown to the user even though the MainActivity (the app's container) has not yet been started.

I build my notification here

private void displayIncomingCallNotification(RemoteMessage remoteMessage) {
        try {
            Map<String, String> data = remoteMessage.getData();
            String messageTimestamp = data.get("timestamp");
            String name = data.get("name");
            String number = data.get("number");

            // If timestamp on push message is outdated then do not send the notification
            if (!checkCallTimeStamp(messageTimestamp)) {
                Log.d(TAG, "Call notification failed timestamp check");
                return;
            }

            if (name.equals(number)) {
                name = FindCallerName(number);
            }

            // Generate bundle containing common data
            Bundle bundle = new Bundle();
            bundle.putString(EXTRA_NAME, name);
            bundle.putString(EXTRA_NUMBER, number);
            bundle.putString(EXTRA_CID, data.get("x-ipc-id"));
            bundle.putString(EXTRA_UUID, data.get("uuid"));
            bundle.putString(EXTRA_GOOGLE_MESSAGE_ID, remoteMessage.getMessageId());

            Intent intent = new Intent(getApplicationContext(), NotificationActivity.class);
            intent.putExtra(EXTRA_NOTIFICATION_ID, 1);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtras(bundle);
            PendingIntent fullScreenPending = PendingIntent.getActivity(this, 2, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            // Intent to answer
            Intent answerIntent = new Intent(getApplicationContext(), NotificationReceiver.class);
            answerIntent.putExtra(EXTRA_NOTIFICATION_ID, 1);
            answerIntent.putExtra(NOTIFICATION_TYPE, TYPE_CALL);
            answerIntent.putExtra(EXTRA_ACTION, ACTION_ANSWER);
            answerIntent.putExtras(bundle);
            PendingIntent answerPending = PendingIntent.getBroadcast(this, 0, answerIntent, PendingIntent.FLAG_CANCEL_CURRENT);

            // Intent to reject
            Intent rejectIntent = new Intent(getApplicationContext(), NotificationReceiver.class);
            rejectIntent.putExtra(EXTRA_NOTIFICATION_ID, 1);
            rejectIntent.putExtra(NOTIFICATION_TYPE, TYPE_CALL);
            rejectIntent.putExtra(EXTRA_ACTION, ACTION_REJECT);
            rejectIntent.putExtras(bundle);
            PendingIntent dismissPending = PendingIntent.getBroadcast(this, 1, rejectIntent, PendingIntent.FLAG_CANCEL_CURRENT);

            // Build custom notification view
            RemoteViews defaultView = new RemoteViews(getPackageName(), R.layout.custom_headsup_notification);
            defaultView.setOnClickPendingIntent(R.id.answer_btn, answerPending);
            defaultView.setOnClickPendingIntent(R.id.reject_btn, dismissPending);
            defaultView.setTextViewText(R.id.notification_title, name);

            // Build and send notification
            NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, CALL_CHANNEL_ID)
                    .setSmallIcon(R.mipmap.ic_launcher_round)
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setCategory(NotificationCompat.CATEGORY_CALL)
                    .setCustomContentView(defaultView)
                    .setAutoCancel(true)
                    .setFullScreenIntent(fullScreenPending, true);

            startVibration();

            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(1, notificationBuilder.build());
        } catch (Exception e) {
            Log.d(TAG, "tried to send call. Resulted in error - " + e);
        }
    }

Doing some digging I found that the SharedUtils.java file uses the package name to determine if that app is in the foreground but the problem is that both the incoming call activity and the main activity have the same package name so its correct from firebase's perspective.

final String packageName = context.getPackageName();
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {

  if (
    appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
      && appProcess.processName.equals(packageName)
  ) {
    ReactContext reactContext;

    try {
      reactContext = (ReactContext) context;
    } catch (ClassCastException exception) {
      // Not react context so default to true
      return true;
    }

    return reactContext.getLifecycleState() == LifecycleState.RESUMED;
  }
}

return false;`

I'm basically wondering if there is any way for firebase to only take into account the main activity or if there is perhaps a different way of implementing this?

Cheers


Project Files

Javascript

Click To Expand

#### `package.json`: ```json { "name": "keevio_mobile", "version": "0.0.1", "private": true, "scripts": { "postinstall": "patch-package", "android": "react-native run-android", "ios": "react-native run-ios", "start": "react-native start", "test": "jest", "lint": "eslint .", "pod-install": "cd ios && pod install && cd ..", "clean-xcode": "cd ios/ && rm -rf build/ && xcodebuild clean && cd .." }, "dependencies": { "@expo/react-native-action-sheet": "^3.8.0", "@fortawesome/fontawesome-svg-core": "^1.2.28", "@fortawesome/pro-light-svg-icons": "^5.13.0", "@fortawesome/pro-regular-svg-icons": "^5.13.0", "@fortawesome/pro-solid-svg-icons": "^5.13.0", "@fortawesome/react-native-fontawesome": "^0.2.5", "@react-native-community/async-storage": "^1.9.0", "@react-native-community/masked-view": "^0.1.9", "@react-native-community/netinfo": "^5.7.0", "@react-native-community/push-notification-ios": "^1.7.1", "@react-native-community/toolbar-android": "^0.1.0-rc.2", "@react-native-firebase/analytics": "^7.6.9", "@react-native-firebase/app": "^8.4.7", "@react-native-firebase/crashlytics": "^8.4.12", "@react-native-firebase/iid": "^7.4.10", "@react-native-firebase/messaging": "^7.9.2", "@react-navigation/bottom-tabs": "^5.2.6", "@react-navigation/compat": "^5.1.8", "@react-navigation/native": "^5.1.5", "@react-navigation/stack": "^5.2.10", "deepmerge": "^4.2.2", "es6-promise-polyfill": "^1.2.0", "hermes-engine": "^0.5.2-rc1", "immer": "^6.0.3", "ipcortex-api": "file:./ipc-api", "jssip": "github:ipcortex/jssip#es6", "prop-types": "^15.7.2", "react": "16.13.1", "react-native": "0.63.4", "react-native-actionsheet": "^2.4.2", "react-native-background-timer": "^2.4.1", "react-native-callkeep": "github:ipcortex/react-native-callkeep#bug/softphoneIssue332-inboundCallDrop", "react-native-config": "^1.2.1", "react-native-contacts": "^5.2.1", "react-native-dark-mode": "^0.2.2", "react-native-device-info": "^5.5.4", "react-native-dropdownalert": "4.2.1", "react-native-elements": "^2.0.4", "react-native-exit-app": "^1.1.0", "react-native-gesture-handler": "^1.6.1", "react-native-image-crop-picker": "^0.28.0", "react-native-incall-manager": "^3.2.7", "react-native-lightweight-responsive": "^0.0.6", "react-native-localization": "^2.1.6", "react-native-navigation-bar-color": "^2.0.1", "react-native-notifications": "^3.2.1", "react-native-permissions": "^3.0.1", "react-native-reanimated": "^1.8.0", "react-native-safe-area-context": "^0.7.3", "react-native-screens": "^2.4.0", "react-native-search-filter": "^0.1.5", "react-native-sensitive-info": "^6.0.0-alpha.9", "react-native-splash-screen": "^3.2.0", "react-native-svg": "^12.1.0", "react-native-tab-view": "^2.14.0", "react-native-toast-message": "^1.3.4", "react-native-vector-icons": "^6.7.0", "react-native-voip-push-notification": "^2.0.0", "react-native-webrtc": "github:nimbleape/react-native-webrtc#84-plus-dtmf-plus-field-trial", "react-redux": "^7.2.0", "redux": "^4.0.5", "redux-logger": "^3.0.6", "redux-persist": "^6.0.0", "redux-persist-transform-encrypt": "^2.0.1", "reselect": "^4.0.0", "time-stamp": "^2.2.0", "tslib": "^1.11.1", "uuid-by-string": "^3.0.2", "valid-url": "^1.0.9" }, "devDependencies": { "@babel/core": "^7.8.4", "@babel/runtime": "^7.8.4", "@react-native-community/eslint-config": "^1.1.0", "babel-jest": "^25.1.0", "babel-plugin-transform-remove-console": "^6.9.4", "eslint": "^6.5.1", "jest": "^25.1.0", "metro-react-native-babel-preset": "^0.59.0", "patch-package": "^6.1.2", "postinstall-postinstall": "^2.0.0", "react-test-renderer": "16.13.1", "redux-immutable-state-invariant": "^2.1.0" }, "jest": { "preset": "react-native" } } ``` #### `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? - [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`: ```groovy // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { ext { googlePlayServicesVersion = "+" // default: "+" firebaseMessagingVersion = "+" // default: "+" buildToolsVersion = "29.0.2" minSdkVersion = 28 //16 compileSdkVersion = 29 targetSdkVersion = 29 } repositories { google() jcenter() maven { url "https://maven.google.com" } } dependencies { classpath("com.android.tools.build:gradle:3.5.3") //classpath("com.android.tools.build:gradle:3.4.1") classpath 'com.google.gms:google-services:4.3.4' classpath 'com.google.firebase:firebase-crashlytics-gradle:2.4.1' // 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") } google() jcenter() maven { url 'https://www.jitpack.io' } maven { url "https://maven.google.com" } } } ``` #### `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. If none specified and * // "index.android.js" exists, it will be used. Otherwise "index.js" is * // default. Can be overridden with ENTRY_FILE environment variable. * entryFile: "index.android.js", * * // https://reactnative.dev/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 = [ enableHermes: true, // clean and rebuild if changing ] 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 /** * 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.keeviomobile" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 1 versionName '1.4' 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://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 project(':react-native-splash-screen') implementation project(':react-native-callkeep') implementation fileTree(dir: "libs", include: ["*.jar"]) //noinspection GradleDynamicVersion implementation "com.facebook.react:react-native:+" // From node_modules implementation "com.android.support:support-compat:28.0.0" implementation "androidx.constraintlayout:constraintlayout:2.0.0" implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0" implementation 'com.google.firebase:firebase-analytics:17.2.3' implementation 'com.google.firebase:firebase-messaging:20.1.3' implementation 'androidx.lifecycle:lifecycle-process:2.2.0' 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 } } apply plugin: 'com.google.gms.google-services' apply plugin: 'com.google.firebase.crashlytics' // 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"); apply from: file("../../node_modules/react-native-vector-icons/fonts.gradle"); applyNativeModulesAppBuildGradle(project) ``` #### `android/settings.gradle`: ```groovy rootProject.name = 'XXXXX' apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings) include ':react-native-callkeep' project(':react-native-callkeep').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-callkeep/android') include ':react-native-splash-screen' project(':react-native-splash-screen').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-splash-screen/android') include ':app' ``` #### `MainApplication.java`: ```java package com.XXXX; import android.app.Application; import android.content.Context; import com.facebook.react.PackageList; import com.facebook.react.ReactApplication; import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.soloader.SoLoader; import java.lang.reflect.InvocationTargetException; import java.util.List; import com.keeviomobile.KeevioNotificationPackage; import com.zxcpoiu.incallmanager.InCallManagerPackage; import io.wazo.callkeep.RNCallKeepPackage; import org.devio.rn.splashscreen.SplashScreenReactPackage; 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()); // packages.add(new WebRTCModulePackage()); // <-- Add this line packages.add(new XXXXNotificationPackage()); 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, getReactNativeHost().getReactInstanceManager()); } /** * Loads Flipper in React Native templates. Call this in the onCreate method with something like * initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); * * @param context * @param reactInstanceManager */ private static void initializeFlipper( Context context, ReactInstanceManager reactInstanceManager) { 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.XXXX.ReactNativeFlipper"); aClass .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class) .invoke(null, context, reactInstanceManager); } 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:** ``` 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`


mikehardy commented 3 years ago

You'll want to be on current versions before attempting anything, in order to make sure we don't waste time with something that is either no longer relevant or needs to be done in a different way:

    "@react-native-firebase/analytics": "^7.6.9",
    "@react-native-firebase/app": "^8.4.7",
    "@react-native-firebase/crashlytics": "^8.4.12",
    "@react-native-firebase/iid": "^7.4.10",
    "@react-native-firebase/messaging": "^7.9.2",

v11.3.3 (with v11.4 coming maybe later today...) is what you'll want to start with. The changelog should help you get through the version bumps, there's nothing that serious in there - we just try to adhere completely semantic-versioning so any small breaking change is a major version https://invertase.io/blog/react-native-firebase-versioning

For what you want, feel free to try anything that seems sensible in SharedUtils and if it looks good post a PR. Bonus points if it's backwards compatible, like a list of Activity names to exclude in firebase.json (backgroundActivityNames or something?) and then on startup in the module you can use the JSON utilities to pull those out (I think?) and alter behavior to suit your case

NIyerAD commented 3 years ago

Thanks for the help, @mikehardy! I'll give those changes a go to start off with a post any developments here

mikehardy commented 3 years ago

Release 11.4.1 just went out with the change related to this among other fixes + features. Enjoy! :rocket: