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.73k stars 2.22k forks source link

šŸ”„ `onNotificationOpenedApp`, `getInitialNotification` not working on Android #4005

Closed calebgregory closed 4 years ago

calebgregory commented 4 years ago

Issue

Hello and good day! I am meeting difficulty using two callbacks that your SDK provides: .onNotificationOpenedApp or .getInitiailNotification

I'm using these methods in the recommended way, and it works on iOS :). But on Android, I'm not seeing success yet. When I press a notification and the app opens, neither the callback I've registered for onNotificationOpenedApp fires, nor does getInitialNotification resolve a remoteMessage when called.

Hypothesis that could lead to a deadend

We're using the python admin SDK to send these push notifications. I've had a hypothesis that in order to have onNotificationOpenedApp fire, we need to specify a click_action at message.android.notification.click_action. That is nothing more than an intuition, but the intuition is based on looking at the @react-native-firebase/messaging implementation.

I see in the factory function remoteMessageToEvent, you conditionally switch the event type to EVENT_NOTIFICATION_OPENED when openEvent = true is given to remoteMessageToEvent as argument.

There is only one case where openEvent = true: in a method-override onNewIntent, which conditionally executes when intent != null.

Thus, I inferred that intent == null. Which implies that I need to do something such that intent != null. :thinking: maybe if I set click_action...

Unfortunately, I don't know whether my hypothesis is correct, nor do I know what are valid values for click_action (i.e., I don't know what are valid intents.) I have looked at the Android activity actions, but I haven't been able to meet success in my trial-and-error approach thus far.

An interesting regression here is that when I include any non-null value for message.android.notification.click_action and I press the notification once it's been delivered to my device, nothing happens. Whereas when I exclude ...click_action from the message payload, pressing the notification opens my app (albiet without the desired call of my-subscriber-to-onNotificationOpenedApp).

Anyway,

Help? At the moment I cannot see what my issue is, but hopefully you can.

// index.js <- note that this is outside of src/ and in <repo-root>

import {
  registerFCMBackgroundMessageHandler,
  registerFCMNotificationOpenedApp,
  checkAppOpenedByNotification,
} from './src/services/push-messaging/init'

registerFCMBackgroundMessageHandler()
registerFCMNotificationOpenedApp()
checkAppOpenedByNotification()

// src/services/push-messaging-init.js

const handleBackgroundMessage = async (remoteMessage) => {
  console.log('handleBackgroundMessage', { remoteMessage, isAppInBackground: true })
}

export function registerFCMBackgroundMessageHandler() {
  messaging().setBackgroundMessageHandler(handleBackgroundMessage)
  console.log(
    'registerFCMBackgroundMessageHandler',
    'successfully registered background message handler with FCM'
  )
}

const handleNotificationOpenedApp = (remoteMessage, wasAppRunningInBackground) => {
  console.log('handleNotificationOpenedApp', {
    remoteMessage,
    wasAppRunningInBackground,
  })
}

export function registerFCMNotificationOpenedApp() {
  messaging().onNotificationOpenedApp((remoteMessage) => {
    handleNotificationOpenedApp(remoteMessage, true)
  })

  console.log(
    'registerFCMNotificationOpenedApp',
    'successfully registered for notification opened app events'
  )
}

export async function checkAppOpenedByNotification() {
  let initialNotification
  try {
    initialNotification = await messaging().getInitialNotification()
  } catch (error) {
    console.error('checkAppOpenedByNotification', 'error getting initialNotification', { error })
    return
  }

  if (initialNotification) {
    handleNotificationOpenedApp(initialNotificaiton, false)
  } else {
    console.log('checkAppOpenedByNotification', 'no initialNotification')
  }
}

Project Files

Javascript

Click To Expand

#### `package.json`: ```json { ... "engines": { "node": "12" }, ... "dependencies": { "@bugfender/rn-bugfender": "^1.1.0", "@emotion/native": "^10.0.14", "@fullstory/babel-plugin-react-native": "^0.9.1", "@react-native-community/async-storage": "^1.5.0", "@react-native-community/hooks": "^2.4.7", "@react-native-community/netinfo": "^4.6.0", "@react-native-firebase/app": "^7.1.4", "@react-native-firebase/messaging": "^7.5.0", "@segment/analytics-react-native": "^1.0.1", "@sentry/react-native": "^1.4.0", "@xoi/net-auth-graphql-client": "1.0.9", "@xoi/vision-jobs-model-layer": "2.4.0", "apollo-client": "^2.6.3", "async-lock": "^1.2.2", "await-timeout": "^0.5.0", "aws-amplify": "^1.1.30", "aws-appsync": "^2.0.0", "aws-appsync-auth-link": "^2.0.1", "aws-appsync-react": "^2.0.0", "buffer": "^5.2.1", "color-convert": "^2.0.0", "debug": "^4.1.1", "events": "^3.1.0", "graphql-tag": "^2.10.1", "jdataview": "^2.5.0", "js-sha256": "^0.9.0", "legalize": "^1.3.0", "lodash": "^4.17.13", "memoize-one": "^5.0.2", "moment": "^2.22.2", "p-retry": "^4.1.0", "ramda": "^0.27.0", "react": "16.11.0", "react-apollo": "^2.2.4", "react-native": "0.62.2", "react-native-actionsheet": "^2.4.2", "react-native-background-fetch": "^2.6.0", "react-native-background-task": "^0.2.1", "react-native-device-info": "^5.3.1", "react-native-exception-handler": "^2.10.8", "react-native-fast-image": "^8.1.5", "react-native-fs": "2.16.6", "react-native-gesture-handler": "^1.6.0", "react-native-image-crop-picker": "~0.25.3", "react-native-image-pan-zoom": "^2.1.11", "react-native-mime-types": "^2.2.1", "react-native-orientation-locker": "^1.1.6", "react-native-pdf": "^6.1.2", "react-native-permissions": "^2.0.3", "react-native-progress": "^3.6.0", "react-native-progress-circle": "^2.0.1", "react-native-reanimated": "^1.7.0", "react-native-render-html": "^4.1.2", "react-native-screens": "^2.0.0-beta.2", "react-native-section-list-get-item-layout": "^2.2.3", "react-native-snackbar": "^2.2.0", "react-native-text-size": "^4.0.0-rc.1", "react-native-thumbnail": "^1.1.3", "react-native-vector-icons": "^6.6.0", "react-native-video": "4.4.4", "react-native-walkme-sdk": "^2.0.12", "react-native-webview": "^8.0.0", "react-navigation": "^4.0.10", "react-navigation-stack": "^1.10.3", "react-navigation-tabs": "^2.5.6", "react-redux": "^7.1.3", "redux": "^4.0.4", "redux-persist": "^6.0.0", "redux-starter-kit": "^1.0.1", "rxjs": "^6.6.0", "styled-system": "^5.0.16", "supports-color": "^7.0.0", "sync-storage": "^0.4.0", "uuid": "^3.3.2", "validatorjs": "3.17.1", }, "devDependencies": { "@babel/core": "^7.8.0", "@babel/preset-flow": "^7.8.0", "@babel/register": "^7.8.0", "@babel/runtime": "^7.8.0", "@emotion/core": "^10.0.14", "@sentry/wizard": "^0.12.1", "@storybook/addon-actions": "^5.1.9", "@storybook/addon-knobs": "^5.3.19", "@storybook/addon-links": "^5.1.9", "@storybook/addon-notes": "^5.1.9", "@storybook/addon-ondevice-knobs": "^5.3.19", "@storybook/addons": "^5.1.9", "@storybook/react-native": "^5.3.19", "@storybook/react-native-server": "^5.3.19", "@types/graphql": "^14.0.7", "apollo": "^2.15.0", "apollo-cache": "^1.3.4", "apollo-cache-inmemory": "^1.6.5", "babel-eslint": "^10.0.2", "babel-jest": "^24.8.0", "babel-loader": "^8.0.6", "casual": "^1.6.2", "chai": "^4.2.0", "emotion-theming": "^10.0.14", "eslint": "^6.5.1", "eslint-config-airbnb": "^17.1.1", "eslint-plugin-flowtype": "^3.11.1", "eslint-plugin-import": "^2.18.0", "eslint-plugin-jsx-a11y": "^6.2.3", "eslint-plugin-react": "^7.14.2", "faker": "^4.1.0", "flow-bin": "^0.110.0", "http-server": "^0.12.1", "husky": "^3.0.0", "jest": "^24.9.0", "jest-watch-typeahead": "^0.3.1", "jetifier": "^1.6.4", "lint-staged": "^9.1.0", "metro-react-native-babel-preset": "^0.58.0", "patch-package": "^6.2.0", "postinstall-postinstall": "^2.0.0", "prettier-eslint": "^9.0.0", "prettier-eslint-cli": "^5.0.0", "react-native-clean-project": "^3.3.0", "react-native-rename": "^2.4.1", "react-native-storybook-loader": "^1.8.1", "react-native-testing-library": "^1.10.0", "react-native-version": "^3.1.0", "react-test-renderer": "16.11.0", "reactotron-react-native": "^3.6.4", "redux-logger": "^3.0.6", "waait": "^1.0.5", }, ... } ``` #### `firebase.json` for react-native-firebase v6: ```json # N/A ```

iOS

(not filling out, because this functionality works on 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? - [ ] I am using `android/gradle.settings` `jetifier=true` for Android compatibility? - [x] I am using the NPM package `jetifier` for react-native compatibility? I checked yes to the `jetifier` question because when I run `react-native run-android`, I get a log ```sh info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag. ``` #### `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 = 24 compileSdkVersion = 28 targetSdkVersion = 28 supportLibVersion = "28.0.0" kotlinVersion = "1.3.61" } repositories { jcenter() maven { url 'https://maven.google.com/' name 'Google' } maven { url "https://maven.fullstory.com" } google() } dependencies { classpath('com.android.tools.build:gradle:3.5.3') classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" classpath 'com.fullstory:gradle-plugin-local:1.2.0' classpath 'com.google.gms:google-services:4.3.3' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { mavenLocal() mavenCentral() 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://maven.google.com/' name 'Google' } maven { url "$rootDir/../node_modules/react-native-background-fetch/android/libs" } maven { url "https://jitpack.io" } jcenter() google() } subprojects { afterEvaluate { project -> if (project.hasProperty("android")) { android { compileSdkVersion = 28 buildToolsVersion = "28.0.3" } } } } } ``` #### `android/app/build.gradle`: ```groovy apply plugin: "com.android.application" apply plugin: "kotlin-android" apply plugin: "kotlin-android-extensions" apply plugin: 'fullstory' 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", bundleConfig: System.getenv('BUNDLE_CONFIG'), enableHermes: false, // clean and rebuild if changing ] apply from: "../../node_modules/react-native/react.gradle" apply from: "../../node_modules/@sentry/react-native/sentry.gradle" apply from: "../../node_modules/react-native-vector-icons/fonts.gradle" /** * Set this to true to create two separate APKs instead of one: * - An APK that only works on ARM devices * - An APK that only works on x86 devices * The advantage is the size of the APK is reduced by about 4MB. * Upload all the APKs to the Play Store and people will download * the correct one based on the CPU architecture of their device. */ def enableSeparateBuildPerCPUArchitecture = false /** * Run Proguard to shrink the Java bytecode in release builds. */ def enableProguardInReleaseBuilds = false /** * 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); /** * Pickup keystore properties if present */ def keystorePropertiesFile = rootProject.file("keystore.properties"); def keystoreProperties = new Properties() keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) fullstory { org 'T4QBZ' enabledVariants 'all' } android { compileSdkVersion rootProject.ext.compileSdkVersion defaultConfig { applicationId "io.xoi.vision" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 15 versionName "1.18.0" ndk { abiFilters "armeabi-v7a", "x86", "arm64-v8a", "x86_64" } multiDexEnabled true } packagingOptions { pickFirst "lib/armeabi-v7a/libc++_shared.so" pickFirst "lib/arm64-v8a/libc++_shared.so" pickFirst "lib/x86/libc++_shared.so" pickFirst "lib/x86_64/libc++_shared.so" } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } splits { abi { reset() enable enableSeparateBuildPerCPUArchitecture universalApk false // If true, also generate a universal APK include "armeabi-v7a", "x86", "arm64-v8a", "x86_64" } } signingConfigs { if (keystoreProperties && keystoreProperties.getProperty('storeFile')) { release { storeFile file(keystoreProperties['storeFile']) storePassword keystoreProperties['storePassword'] keyAlias keystoreProperties['keyAlias'] keyPassword keystoreProperties['keyPassword'] } } else { release { } } } buildTypes { release { minifyEnabled enableProguardInReleaseBuilds proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" signingConfig signingConfigs.release } } flavorDimensions "vision" productFlavors { prod { dimension "vision" } ea { dimension "vision" applicationIdSuffix ".ea" versionNameSuffix "-ea" } dev { dimension "vision" applicationIdSuffix ".dev" versionNameSuffix "-dev" } demo { dimension "vision" applicationIdSuffix ".demo" versionNameSuffix "-demo" } local { dimension "vision" applicationIdSuffix ".local" versionNameSuffix "-local" } } // 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 'androidx.multidex:multidex:2.0.1' implementation project(':react-native-text-size') implementation project(':react-native-background-task') // kotlin implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3" // image picker library implementation 'com.zhihu.android:matisse:0.5.3-beta3' // required by com.zhihu.android:matisse implementation 'com.github.bumptech.glide:glide:4.8.0' // required by com.github.bumptech.glide implementation project(path: ":@react-native-firebase_app") implementation project(path: ":@react-native-firebase_messaging") annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0' implementation project(':amazon-cognito-identity-js') implementation fileTree(include: ['*.jar'], dir: 'libs') implementation 'com.facebook.react:react-native:+' implementation 'com.googlecode.mp4parser:isoparser:1.1.21' // From node_modules api 'com.google.guava:guava:26.0-android' // https://github.com/google/guava implementation 'androidx.appcompat:appcompat:1.1.0-rc01' implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-alpha02' implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.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' } 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 from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle") applyNativeModulesAppBuildGradle(project) // 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' } task devJetify(type: Exec) { workingDir "$projectDir/../../scripts" commandLine './quick-jetify.sh' ignoreExitValue true doLast { if (execResult.exitValue != 0) { println "Error encountered during jetify" } } } clean.dependsOn devJetify apply plugin: 'com.google.gms.google-services' ``` #### `android/settings.gradle`: ```groovy rootProject.name = 'VisionNxMobile' include ':react-native-text-size' project(':react-native-text-size').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-text-size/android') include ':react-native-background-task' project(':react-native-background-task').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-background-task/android') apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings) include ':amazon-cognito-identity-js' project(':amazon-cognito-identity-js').projectDir = new File(rootProject.projectDir, '../node_modules/amazon-cognito-identity-js/android') include ':react-native-video' project(':react-native-video').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-video/android-exoplayer') include ':@react-native-firebase_app' project(':@react-native-firebase_app').projectDir = new File(rootProject.projectDir, './../node_modules/@react-native-firebase/app/android') include ':@react-native-firebase_messaging' project(':@react-native-firebase_messaging').projectDir = new File(rootProject.projectDir, '../node_modules/@react-native-firebase/messaging/android') include ':app' ``` #### `MainApplication.java`: ```java package io.xoi.vision; import java.util.Arrays; import java.util.List; import android.app.Application; import android.content.Context; import android.util.Log; import androidx.multidex.MultiDex; import androidx.multidex.MultiDexApplication; import com.facebook.react.PackageList; import com.facebook.hermes.reactexecutor.HermesExecutorFactory; import com.facebook.react.bridge.JavaScriptExecutorFactory; import com.facebook.react.ReactApplication; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import com.facebook.soloader.SoLoader; import com.facebook.react.modules.storage.ReactDatabaseSupplier; import com.amazonaws.RNAWSCognitoPackage; import com.jamesisaac.rnbackgroundtask.BackgroundTaskPackage; import com.github.amarcruz.rntextsize.RNTextSizePackage; import io.xoi.fullstory.FullStoryPackage; import io.xoi.vision.VisionGeneralPackage; import io.xoi.vision.CopyFileByteRangePackage; import io.xoi.documentationcopier.DocumentationCopierPackage; import io.xoi.videoresampler.RNVideoResamplerPackage; import io.xoi.mediapicker.MediaPickerPackage; import com.facebook.react.ReactInstanceManager; import java.lang.reflect.InvocationTargetException; // FullStory tracking requires the MainApplication to extend MultiDexApplication public class MainApplication extends MultiDexApplication implements ReactApplication { static final long ASYNC_STORAGE_SIZE_BYTES = 50L * 1024L * 1024L; // 50 MB private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List getPackages() { List packages = new PackageList(this).getPackages(); packages.add(new SplashScreenPackage()); packages.add(new RNAWSCognitoPackage()); /** * XOi Native Module Packages */ packages.add(new RNVideoResamplerPackage()); packages.add(new VersionManagerPackage()); packages.add(new CopyFileByteRangePackage()); packages.add(new VisionGeneralPackage()); packages.add(new MediaPickerPackage()); packages.add(new DocumentationCopierPackage()); packages.add(new FullStoryPackage()); return packages; } @Override protected String getJSMainModuleName() { return "index"; } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); BackgroundTaskPackage.useContext(this); SoLoader.init(this, /* native exopackage */ false); initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); } @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); MultiDex.install(this); } /** * 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.rndiffapp.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:** ``` info Fetching system and libraries information... System: OS: macOS 10.15.5 CPU: (16) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz Memory: 25.21 MB / 16.00 GB Shell: 5.7.1 - /bin/zsh Binaries: Node: 12.17.0 - ~/.nvm/versions/node/v12.17.0/bin/node Yarn: 1.22.4 - /usr/local/bin/yarn npm: 6.14.4 - ~/.nvm/versions/node/v12.17.0/bin/npm Watchman: 4.9.0 - /usr/local/bin/watchman Managers: CocoaPods: 1.9.2 - /usr/local/bin/pod SDKs: iOS SDK: Platforms: iOS 13.4, DriverKit 19.0, macOS 10.15, tvOS 13.4, watchOS 6.2 Android SDK: API Levels: 28, 29 Build Tools: 28.0.3, 29.0.3 System Images: android-28 | Intel x86 Atom_64, android-28 | Google APIs Intel x86 Atom_64, android-29 | Google APIs Intel x86 Atom, android-29 | Google Play Intel x86 Atom Android NDK: Not Found IDEs: Android Studio: 3.6 AI-192.7142.36.36.6392135 Xcode: 11.4.1/11E503a - /usr/bin/xcodebuild Languages: Java: 1.8.0_252 - /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home/bin/javac Python: 3.7.6 - /Users/calebgregory/miniconda/bin/python npmPackages: @react-native-community/cli: Not Found react: 16.11.0 => 16.11.0 react-native: 0.62.2 => 0.62.2 npmGlobalPackages: *react-native*: Not Found ``` - **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. 7.5.0` - **`Firebase` module(s) you're using that has the issue:** - `e.g. Messaging` - **Are you using `TypeScript`?** - N


honeyp0t commented 4 years ago

This might not be terribly useful but I don't think you should mess with click_action normally. I did so in my app and the result was that the app would not open when tapping on a notification. I have gotten the callbacks working in my app without touching click_action.

Do notifications work otherwise, and it's just these callbacks that are causing issues?

calebgregory commented 4 years ago

hey @honeyp0t, thank you for the response!

I'm seeing the same behavior you describe while messing with click_action - setting it to any value makes it such that the app doesn't open when the notification is pressed.

Yes - everything else works on Android (I can register with FCM and get messages onMessage šŸ‘ ); it's just onNotificationOpenedApp and getInitialNotification that are not working.

(edit) I've edited the original post description to make that a bit clearer. Thank you for asking for clarification!

mikehardy commented 4 years ago

What's the SplashActivity? It's probably eating the Intent or enough of the Intent so that react-native-firebase can't put things together for you.

Use react-native-bootsplash - it works. Others don't (cf. https://github.com/crazycodeboy/react-native-splash-screen/issues/289#issuecomment-502406454)

OmarBasem commented 4 years ago

I tried react-native-bootsplash but onNotificationOpenedApp and getInitialNotification are still not working!

calebgregory commented 4 years ago

@mikehardy I wound up not using react-native-bootsplash as you suggested, but you were right about the SplashActivity swallowing the Intent. We have a custom SplashActivity implementation that is very bare-bones; I'll share the diffs for anyone interested, and maybe some of you can offer insight into why my solution works.

Summary

  1. com.mycompany.myapp.SplashActivity extends ReactActivity, not AppCompatActivity, and
  2. any .mExtras that were on the original MainActivity intent are copied onto the the intent instantiated by com.mycompany.myapp.SplashActivity.

diffs

diff --git a/android/app/src/main/java/com/mycompany/myapp/SplashActivity.java b/android/app/src/main/java/com/mycompany/myapp/SplashActivity.java
index a827e27f..494a9945 100644
--- a/android/app/src/main/java/com/mycompany/myapp/SplashActivity.java
+++ b/android/app/src/main/java/com/mycompany/myapp/SplashActivity.java
@@ -2,15 +2,35 @@ package com.mycompany.myapp;

 import android.content.Intent;
 import android.os.Bundle;
-import androidx.appcompat.app.AppCompatActivity;
+import com.facebook.react.ReactActivity;

-public class SplashActivity extends AppCompatActivity {
+// SplashActivity must extend ReactActivity (and not AppCompatActivity) in order
+// for Push Notifications to call onNotificationOpenedApp or for
+// getInitialNotification to resolve a value
+public class SplashActivity extends ReactActivity {
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);

-        Intent intent = new Intent(this, MainActivity.class);
-        startActivity(intent);
-        finish();
+        try {
+            Intent intent = new Intent(this, MainActivity.class);
+            Bundle extras = getIntent().getExtras();
+
+            if (extras != null) {
+                // this line is critical for Push Notifications to call
+                // onNotificationOpenedApp
+                intent.putExtras(extras);
+            }
+
+            intent.setAction(getIntent().getAction());
+            intent.setData(getIntent().getData());
+
+            startActivity(intent);
+            finish();
+        } catch (Exception e) {
+            e.printStackTrace();
+            finishAffinity();
+        }
     }
 }

Premise

We have our own custom implementation of SplashActivity - presumably for a reason, right? @mikehardy recommended I use react-native-bootsplash. Although I did try this, it seemed very wasteful to annihilate the existing SplashActivity functionality that was our own (and therefore easily changeable) to replace it with something that "just works" even though we don't understand or have control over it.

For more information about action.intents, see the android documentation. Bundle extras, you could think of as being a bundle of metadata attached to the activity.intent. The primary issue is that something was swallowing these extras prior to the Intent making it to @react-native-firebase/messaging's code for handling Intents.

Solution

The solution here is twofold:

  1. Use ReactActivity instead of AppCompatActivity

    • (ReactActivity extends AppCompatActivity)
    • The behavior of [ReactActivity].getIntent() is different than [AppCompatActivity].getIntent()
    • The intent returned from [AppCompatActivity].getIntent() had no .mExtras on it šŸ¤”
    • Why is this? I don't really know...
      • the ReactActivity overrides of the AppCompatActivity methods call each of the respective methods on mDelegate, a ReactActivityDelegate. It may have something to do with that.
    • I saw that ReactActivity was used rather than AppCompatActivity in our App's MainActivity class, which tipped me off to the possibility of changing SplashActivity to similarly extend ReactActivity.
  2. Copy the original "intent qualities" (extras, action, data) onto the newly-instantiated intent inside SplashActivity.onCreate.

    @OmarBasem I hope this offers some insight. In order to reach this solution, I had to learn how to use the Android Studio debugger to inspect the intent instantiated within my custom SplashActivity.onCreate method. There's no way I could have come to this solution without that.

    @mikehardy - thank you so much for your response! It was extremely helpful and deeply appreciated :).

theodorusyoga commented 4 years ago

Hello, this still happened to me, I didn't receive remote message on getInitialNotification() (the value was null), even though I removed react-native-splash-screen and changed AndroidManifest.xml back to MainActivity as android.intent.action.MAIN and android.intent.category.LAUNCHER.

I also tried @calebgregory code for SplashActivity.java (when react-native-splash-screen still installed) but it still didn't work. Any idea why?

Here is my AndroidManifest.xml with splash activity:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.xyz"
  xmlns:tools="http://schemas.android.com/tools">

     <!-- PERMISSIONS HERE -->

    <!-- TODO: Remove "android:usesCleartextTraffic" when we use HTTPS to get video call session id -->
    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:usesCleartextTraffic="true"
      android:allowBackup="false"
      android:theme="@style/AppTheme">

      <activity
        android:name=".SplashActivity"
        android:theme="@style/SplashScreen_Fullscreen"
        android:label="@string/app_name"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>

      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize"
        android:exported="true"/>

      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />

      <!-- other activities -->

      <!-- @react-native-firebase/messaging's config -->
      <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@mipmap/ic_notification_icon" />
      <meta-data
        android:name="com.google.firebase.messaging.default_notification_color"
        android:resource="@color/primary"
        tools:replace="android:resource"
      />
    </application>
</manifest>

And I changed without splash activity, so I changed MainActivity part on the file and removed activity for SplashActivity:

<activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize"
        android:exported="true">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        </activity>

I tried to debug on Android Studio but it won't let me debug when the app is already killed. Any suggestions how to do this?

Thanks a bunch!

mikehardy commented 4 years ago

@theodorusyoga use react-native-boot-splash for splash screen, it doesn't have these problems and the other package you mention is no longer maintained. There must be something with your project as I can't reproduce this in mine. You might try doing a minimal reproduction built off https://github.com/mikehardy/rnfbdemo/blob/master/make-demo.sh to see if you can show the problem

stale[bot] commented 4 years 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 the community's attention?

This issue will be closed in 15 days if no further activity occurs. Thank you for your contributions.

0xamogh commented 4 years ago

@calebgregory Thanks for this! Would have taken days to figure this out, works like a charm šŸ˜ƒ

stale[bot] commented 4 years 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 the community's attention?

This issue will be closed in 15 days if no further activity occurs. Thank you for your contributions.

idotalmor commented 4 years ago

@calebgregory job saver šŸ‘

mibmol commented 4 years ago

@calebgregory Thank you so much. I spend almost a day trying to solve this :)

yinmingdi commented 3 years ago

@calebgregory Thank you so much. šŸ‘

Aleclindner commented 3 years ago

@calebgregory the best

MuriloDutra commented 2 years ago

@mikehardy I wound up not using react-native-bootsplash as you suggested, but you were right about the SplashActivity swallowing the Intent. We have a custom SplashActivity implementation that is very bare-bones; I'll share the diffs for anyone interested, and maybe some of you can offer insight into why my solution works.

Summary

  1. com.mycompany.myapp.SplashActivity extends ReactActivity, not AppCompatActivity, and
  2. any .mExtras that were on the original MainActivity intent are copied onto the the intent instantiated by com.mycompany.myapp.SplashActivity.

diffs

diff --git a/android/app/src/main/java/com/mycompany/myapp/SplashActivity.java b/android/app/src/main/java/com/mycompany/myapp/SplashActivity.java
index a827e27f..494a9945 100644
--- a/android/app/src/main/java/com/mycompany/myapp/SplashActivity.java
+++ b/android/app/src/main/java/com/mycompany/myapp/SplashActivity.java
@@ -2,15 +2,35 @@ package com.mycompany.myapp;

 import android.content.Intent;
 import android.os.Bundle;
-import androidx.appcompat.app.AppCompatActivity;
+import com.facebook.react.ReactActivity;

-public class SplashActivity extends AppCompatActivity {
+// SplashActivity must extend ReactActivity (and not AppCompatActivity) in order
+// for Push Notifications to call onNotificationOpenedApp or for
+// getInitialNotification to resolve a value
+public class SplashActivity extends ReactActivity {
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);

-        Intent intent = new Intent(this, MainActivity.class);
-        startActivity(intent);
-        finish();
+        try {
+            Intent intent = new Intent(this, MainActivity.class);
+            Bundle extras = getIntent().getExtras();
+
+            if (extras != null) {
+                // this line is critical for Push Notifications to call
+                // onNotificationOpenedApp
+                intent.putExtras(extras);
+            }
+
+            intent.setAction(getIntent().getAction());
+            intent.setData(getIntent().getData());
+
+            startActivity(intent);
+            finish();
+        } catch (Exception e) {
+            e.printStackTrace();
+            finishAffinity();
+        }
     }
 }

Premise

We have our own custom implementation of SplashActivity - presumably for a reason, right? @mikehardy recommended I use react-native-bootsplash. Although I did try this, it seemed very wasteful to annihilate the existing SplashActivity functionality that was our own (and therefore easily changeable) to replace it with something that "just works" even though we don't understand or have control over it.

For more information about action.intents, see the android documentation. Bundle extras, you could think of as being a bundle of metadata attached to the activity.intent. The primary issue is that something was swallowing these extras prior to the Intent making it to @react-native-firebase/messaging's code for handling Intents.

Solution

The solution here is twofold:

  1. Use ReactActivity instead of AppCompatActivity
  • (ReactActivity extends AppCompatActivity)
  • The behavior of [ReactActivity].getIntent() is different than [AppCompatActivity].getIntent()

    • The intent returned from [AppCompatActivity].getIntent() had no .mExtras on it šŸ¤”

    • Why is this? I don't really know...

    • the ReactActivity overrides of the AppCompatActivity methods call each of the respective methods on mDelegate, a ReactActivityDelegate. It may have something to do with that.

  • I saw that ReactActivity was used rather than AppCompatActivity in our App's MainActivity class, which tipped me off to the possibility of changing SplashActivity to similarly extend ReactActivity.
  1. Copy the original "intent qualities" (extras, action, data) onto the newly-instantiated intent inside SplashActivity.onCreate.

@OmarBasem I hope this offers some insight. In order to reach this solution, I had to learn how to use the Android Studio debugger to inspect the intent instantiated within my custom SplashActivity.onCreate method. There's no way I could have come to this solution without that.

@mikehardy - thank you so much for your response! It was extremely helpful and deeply appreciated :).

Worked like a charm, thanks man!

mikehardy commented 2 years ago

The problem with doing it yourself is that ...then you have to do it all yourself. You should know Android 12 changed how app splash screens work entirely. And react-native-bootsplash has already adapted to it, but if you've rolled your own custom solution now you have to handle it yourself too...

MuriloDutra commented 2 years ago

@mikehardy it's a good point, I only did it like that because I already have react-native-bootsplash, but onNotificationOpenedApp and getInitialNotification still weren't working properly. I'm gonna test my app on Android 12 to see how it goes.

devrmateo commented 2 years ago

Just had to deal with this issue. Our app was using react-native-splash-screen and neither of the notification handlers were getting called on Android, while only one was getting called correctly on iOS. Rather than mess around with native code, I decided to bite the bullet and install rn-bootsplash as @mikehardy has recommended. Is it a bit of extra work? Yes. Is it worth it? Imo, yes, because now both handlers are working correctly on both iOS and Android. Thanks Mike!

erenkulaksiz commented 1 month ago

Hello, after removing react-native-splash-screen, trying to write native java module, trying to tweak my android manifest none of them worked. but i found a simple solution. I was using "react-native-push-notification" along with fcm, i now uninstalled that package, and i can get onNotificationOpenedApp callbacks correctly.

AliAshfaq-Gol commented 1 month ago

After struggling for two days to resolve the issue, I finally fixed it by removing the "click-action" from the notification object on the backend, and now everything is working perfectly.