react-native-firebase icon indicating copy to clipboard operation
react-native-firebase copied to clipboard

[🐛] 🔥 Creating a notification inside custom FirebaseMessagingService makes app not trigger onNotificationOpenedApp()

Open rgbedin opened this issue 4 years ago • 4 comments

Issue

I am escalating this to an issue cause I believe it might be a bug inside the library. However please feel free to correct me if I am making the wrong assumption here.

Discussed in https://github.com/invertase/react-native-firebase/discussions/5018

Originally posted by rgbedin March 11, 2021 First of, thanks for dedicating code to our community.

In my application I implement a custom FirebaseMessagingService -- all messages that are sent via push to the client are encrypted. Therefore I need to intercept all pushes to be able to decrypt the notification body and title. Everything works fine: I am able to receive the message on the onMessageReceived() method. I then decrypt and create a new local notification:

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    if (remoteMessage.getData().size() > 0) {
        try {
            JSONObject jsonObject = new JSONObject(remoteMessage.getData());
            displayCustomNotification(jsonObject.getString("title"), jsonObject.getString("body"));
        } catch (JSONException err) {
            err.printStackTrace();
        }
    }
}

@RequiresApi(api = Build.VERSION_CODES.N)
public void displayCustomNotification(String title, String body) {
    boolean isOnForeground = foregrounded();

    if (isOnForeground) {
        return;
    }

    if (notificationManager == null) {
        notificationManager = (NotificationManager) getSystemService (Context.NOTIFICATION_SERVICE);
    }

    Long tsLong = System.currentTimeMillis()/1000;
    int timestamp = Math.toIntExact(tsLong);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    Intent intent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 1251, intent, PendingIntent.FLAG_ONE_SHOT);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    int importance = NotificationManager.IMPORTANCE_HIGH;
    String channel = "channel";

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channel);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        if (mChannel == null) {
            mChannel = new NotificationChannel(tauriaChannel, title, importance);
            mChannel.setDescription(body);
            mChannel.enableVibration(true);
            notificationManager.createNotificationChannel(mChannel);
        }

        notificationBuilder
            .setContentTitle(title)
            .setSmallIcon(R.drawable.ic_tauria_notification)
            .setContentText(bodyWithKey)
            .setDefaults(Notification.DEFAULT_ALL)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .setSound(defaultSoundUri);

        notificationManager.notify(timestamp, notificationBuilder.build());
    } else {
        notificationBuilder
            .setContentTitle(title)
            .setContentText(bodyWithKey)
            .setAutoCancel(true)
            .setColor(ContextCompat.getColor(getBaseContext(), R.color.black))
            .setSound(defaultSoundUri)
            .setSmallIcon(R.drawable.ic_tauria_notification)
            .setContentIntent(pendingIntent)
            .setStyle(new NotificationCompat.BigTextStyle().setBigContentTitle(title).bigText(body));

        notificationManager.notify(timestamp, notificationBuilder.build());
    }
}

The notification is successfully displayed to the user, even if the app is on dead state. I also receive the callback from messaging().setBackgroundMessageHandler() just fine. My issue is that I am trying to detect if the user tapped the notification to open the app, but neither the onNotificationOpenedApp() or messaging().getInitialNotification() is triggered.

Moreover, these listeners do work fine if I just send a notification with a "notification": { "title": "test" }"; however that makes the OS to not pass that through my custom FirebaseMessagingService and display rightaway to the user.

I tried digging into the source code and I realized that maybe my custom FirebaseMessagingService was not setting some expected properties inside the intent that I am creating. Therefore I tried adding the following code, but with no success as well:

intent.putExtra("launchedFromNotification", "true");
intent.putExtra("messageId", "0:2615498316804087%40f8bc8040f8bc80");
intent.putExtra("message_id", "0:2615498316804087%40f8bc8040f8bc80");
intent.putExtra("collapseKey", "com.myapp.mobileapp");
intent.putExtra("from", "329957935616");
intent.putExtra("sentTime", "1615499164445");
intent.putExtra("google.message_id", "0:3615498316804087%40f8bc8040f8bc80");
intent.putExtra("gcm.n.e", "1");
intent.putExtra("gcm.notification.e", "1");

Does anyone have any insight on how I can make my custom created notification being able to be detected by the onNotificationOpenedApp() callback?

Moreover: I recently updated to v12.9.0 of @react-native-firebase/messaging and no luck. I also tried extending my custom service from ReactNativeFirebaseMessagingService instead of FirebaseMessagingService; no luck as well.
Thank you!

Project Files

Javascript

Click To Expand

package.json:

{
  "name": "App",
  "version": "0.4.0",
  "private": true,
  "scripts": {
    "ios": "react-native run-ios",
    "ios:deploy": "react-native bundle --entry-file index.js --platform ios --dev false --bundle-output ios/main.jsbundle --assets-dest ios --reset-cache",
    "android": "react-native run-android",
    "android:clean": "cd android && ./gradlew clean && cd ..",
    "android:cleanstart": "yarn android:clean && react-native run-android",
    "android:deploy": "yarn jetify && yarn android:clean && react-native bundle --entry-file index.js --platform android --dev false --bundle-output android/app/src/main/assets/app.bundle && bash fix-android-deploy.sh && cd android && ./gradlew assembleRelease && cd ..",
    "start": "react-native start",
    "test": "jest",
    "code:check": "yarn code:lint && yarn code:format --check && yarn code:types",
    "code:clean": "yarn code:lint --fix; yarn code:format --write",
    "code:lint": "eslint ./src --ext .js,.jsx,.ts,.tsx",
    "code:format": "prettier './src/**/**.{js,jsx,ts,tsx}'",
    "code:types": "tsc --noemit",
    "generate": "env-cmd -f .env.codegen graphql-codegen",
    "generate:watch": "yarn run generate --watch",
    "bump-patch": "npm version patch --no-git-tag-version && bundle exec fastlane bump",
    "bump-minor": "npm version minor --no-git-tag-version && bundle exec fastlane bump",
    "bump-major": "npm version major --no-git-tag-version && bundle exec fastlane bump"
  },
  "dependencies": {
    "@apollo/client": "^3.3.19",
    "@developers/lib-app-encryption": "^0.8.14",
    "@developers/react-native-controlled-mentions": "^2.3.0-1",
    "@developers/app-auth-react-library-core": "3.6.4",
    "@developers/app-file-react-lib": "^2.0.20",
    "@react-native-async-storage/async-storage": "react-native-async-storage/async-storage",
    "@react-native-clipboard/clipboard": "^1.8.2",
    "@react-native-community/art": "^1.2.0",
    "@react-native-community/masked-view": "^0.1.10",
    "@react-native-community/netinfo": "^5.9.10",
    "@react-native-firebase/analytics": "^12.9.0",
    "@react-native-firebase/app": "^12.9.0",
    "@react-native-firebase/messaging": "^12.9.0",
    "@react-navigation/drawer": "^5.8.4",
    "@react-navigation/native": "^5.8.10",
    "@react-navigation/stack": "^5.12.8",
    "@stream-io/flat-list-mvcp": "^0.0.9",
    "@types/bytes": "^3.1.0",
    "@types/i18n-js": "^3.8.0",
    "@types/react-native-shared-group-preferences": "^1.1.0",
    "@types/styled-components": "^5.1.9",
    "@zxing/text-encoding": "^0.9.0",
    "apollo-link-offline": "^1.0.1",
    "apollo3-cache-persist": "^0.9.1",
    "axios": "^0.21.0",
    "babel-plugin-module-resolver": "^4.0.0",
    "base64-arraybuffer": "^0.2.0",
    "buffer": "^6.0.3",
    "bytes": "^3.1.0",
    "date-fns": "^2.22.1",
    "emoji-regex": "^10.0.0",
    "graphql": "^15.4.0",
    "graphql-ws": "^5.4.0",
    "i18n-js": "^3.8.0",
    "lodash": "^4.17.20",
    "lottie-ios": "3.1.8",
    "lottie-react-native": "^4.0.0",
    "luxon": "^1.25.0",
    "node-forge": "^0.10.0",
    "polished": "^4.0.5",
    "randomcolor": "^0.6.2",
    "react": "17.0.1",
    "react-native": "0.64.2",
    "react-native-app-link": "^1.0.1",
    "react-native-bootsplash": "^3.1.5",
    "react-native-confirmation-code-field": "^7.1.0",
    "react-native-device-info": "^8.1.3",
    "react-native-dialog": "^6.1.2",
    "react-native-document-picker": "^5.0.3",
    "react-native-fast-image": "^8.3.4",
    "react-native-file-viewer": "^2.1.4",
    "react-native-flash-message": "^0.1.23",
    "react-native-fs": "^2.18.0",
    "react-native-gesture-handler": "^1.6.1",
    "react-native-get-random-values": "^1.5.1",
    "react-native-image-picker": "4.0.3",
    "react-native-inappbrowser-reborn": "^3.5.1",
    "react-native-indicators": "^0.17.0",
    "react-native-iphone-x-helper": "^1.3.1",
    "react-native-linear-gradient": "^2.5.6",
    "react-native-localize": "^2.0.1",
    "react-native-logs": "^3.0.3",
    "react-native-mail": "^6.1.0",
    "react-native-modal": "^11.6.1",
    "react-native-parsed-text": "^0.0.22",
    "react-native-permissions": "^3.0.3",
    "react-native-polyfill-globals": "^3.1.0",
    "react-native-progress": "^4.1.2",
    "react-native-reanimated": "^2.0.0",
    "react-native-safe-area-context": "^3.0.7",
    "react-native-screens": "^2.9.0",
    "react-native-set-soft-input-mode": "^1.1.0",
    "react-native-share": "^6.2.1",
    "react-native-shared-group-preferences": "^1.1.20",
    "react-native-shimmer-placeholder": "^2.0.6",
    "react-native-status-bar-height": "^2.6.0",
    "react-native-svg": "^12.1.0",
    "react-native-svg-transformer": "^0.14.3",
    "react-native-version-check": "^3.4.2",
    "react-native-version-info": "^1.1.0",
    "styled-components": "^5.1.1",
    "subscriptions-transport-ws": "^0.9.18",
    "uuid": "^8.3.2",
    "web-encoding": "^1.1.5",
    "web-streams-polyfill": "^3.0.3"
  },
  "devDependencies": {
    "@babel/core": "^7.6.2",
    "@babel/runtime": "^7.6.2",
    "@graphql-codegen/add": "^2.0.2",
    "@graphql-codegen/cli": "^1.20.0",
    "@graphql-codegen/fragment-matcher": "^2.0.1",
    "@graphql-codegen/introspection": "^1.18.1",
    "@graphql-codegen/typescript": "^1.20.0",
    "@graphql-codegen/typescript-apollo-client-helpers": "^1.1.2",
    "@graphql-codegen/typescript-operations": "^1.17.13",
    "@graphql-codegen/typescript-react-apollo": "^2.2.1",
    "@react-native-community/eslint-config": "^1.0.0",
    "@types/axios": "^0.14.0",
    "@types/base64-arraybuffer": "^0.1.0",
    "@types/jest": "^24.0.24",
    "@types/lodash": "^4.14.168",
    "@types/luxon": "^1.25.1",
    "@types/node-forge": "^0.9.7",
    "@types/randomcolor": "^0.5.5",
    "@types/react-native": "^0.63.50",
    "@types/react-native-app-link": "^1.0.0",
    "@types/react-native-dialog": "^5.6.3",
    "@types/react-native-indicators": "^0.16.0",
    "@types/react-native-version-check": "^3.4.2",
    "@types/react-test-renderer": "16.9.2",
    "@types/styled-components-react-native": "^5.1.1",
    "@types/uuid": "^8.3.0",
    "@typescript-eslint/eslint-plugin": "^3.4.0",
    "@typescript-eslint/parser": "^3.4.0",
    "babel-jest": "^24.9.0",
    "env-cmd": "^10.1.0",
    "eslint": "^7.3.1",
    "eslint-plugin-react": "^7.20.0",
    "eslint-plugin-react-hooks": "^4.0.4",
    "husky": "^4.2.5",
    "jest": "^24.9.0",
    "lint-staged": "^10.2.11",
    "metro-react-native-babel-preset": "^0.58.0",
    "prettier": "^2.0.4",
    "react-native-flipper": "^0.75.1",
    "react-native-flipper-apollo-devtools": "^0.0.2",
    "react-native-version": "^4.0.0",
    "react-test-renderer": "16.11.0",
    "typescript": "^3.8.3"
  },
  "jest": {
    "preset": "react-native",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ]
  },
  "husky": {
    "hooks": {
      "pre-commit": "yarn code:check && lint-staged"
    }
  },
  "lint-staged": {
    "*.{js,ts,tsx}": [
      "git add"
    ]
  },
  "resolutions": {
    "@types/**/@types/react-native": "0.63.52"
  }
}

firebase.json for react-native-firebase v6:

# N/A

iOS

Click To Expand

ios/Podfile:

  • [ ] I'm not using Pods
  • [x] I'm using Pods and my Podfile looks like:
platform :ios, '10.0'

require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

def add_flipper_pods!(versions = {})
  versions['Flipper'] ||= '~> 0.33.1'
  versions['DoubleConversion'] ||= '1.1.7'
  versions['Flipper-Folly'] ||= '~> 2.1'
  versions['Flipper-Glog'] ||= '0.3.6'
  versions['Flipper-PeerTalk'] ||= '~> 0.0.4'
  versions['Flipper-RSocket'] ||= '~> 1.0'

  pod 'FlipperKit', versions['Flipper'], :configuration => 'Debug'
  pod 'FlipperKit/FlipperKitLayoutPlugin', versions['Flipper'], :configuration => 'Debug'
  pod 'FlipperKit/SKIOSNetworkPlugin', versions['Flipper'], :configuration => 'Debug'
  pod 'FlipperKit/FlipperKitUserDefaultsPlugin', versions['Flipper'], :configuration => 'Debug'
  pod 'FlipperKit/FlipperKitReactPlugin', versions['Flipper'], :configuration => 'Debug'

  # List all transitive dependencies for FlipperKit pods
  # to avoid them being linked in Release builds
  pod 'Flipper', versions['Flipper'], :configuration => 'Debug'
  pod 'Flipper-DoubleConversion', versions['DoubleConversion'], :configuration => 'Debug'
  pod 'Flipper-Folly', versions['Flipper-Folly'], :configuration => 'Debug'
  pod 'Flipper-Glog', versions['Flipper-Glog'], :configuration => 'Debug'
  pod 'Flipper-PeerTalk', versions['Flipper-PeerTalk'], :configuration => 'Debug'
  pod 'Flipper-RSocket', versions['Flipper-RSocket'], :configuration => 'Debug'
  pod 'FlipperKit/Core', versions['Flipper'], :configuration => 'Debug'
  pod 'FlipperKit/CppBridge', versions['Flipper'], :configuration => 'Debug'
  pod 'FlipperKit/FBCxxFollyDynamicConvert', versions['Flipper'], :configuration => 'Debug'
  pod 'FlipperKit/FBDefines', versions['Flipper'], :configuration => 'Debug'
  pod 'FlipperKit/FKPortForwarding', versions['Flipper'], :configuration => 'Debug'
  pod 'FlipperKit/FlipperKitHighlightOverlay', versions['Flipper'], :configuration => 'Debug'
  pod 'FlipperKit/FlipperKitLayoutTextSearchable', versions['Flipper'], :configuration => 'Debug'
  pod 'FlipperKit/FlipperKitNetworkPlugin', versions['Flipper'], :configuration => 'Debug'
end

# Post Install processing for Flipper
def flipper_post_install(installer)
  installer.pods_project.targets.each do |target|
    if target.name == 'YogaKit'
      target.build_configurations.each do |config|
        config.build_settings['SWIFT_VERSION'] = '4.1'
      end
    end
  end
end

target 'App' do
  config = use_native_modules!

  use_react_native!(
    :path => config[:reactNativePath],
    # to enable hermes on iOS, change `false` to `true` and then install pods
    :hermes_enabled => false
  )

  # Pods for App
  pod 'FBLazyVector', :path => "../node_modules/react-native/Libraries/FBLazyVector"
  pod 'FBReactNativeSpec', :path => "../node_modules/react-native/React/FBReactNativeSpec"
  pod 'RCTRequired', :path => "../node_modules/react-native/Libraries/RCTRequired"
  pod 'RCTTypeSafety', :path => "../node_modules/react-native/Libraries/TypeSafety"
  pod 'React', :path => '../node_modules/react-native/'
  pod 'React-Core', :path => '../node_modules/react-native/'
  pod 'React-CoreModules', :path => '../node_modules/react-native/React/CoreModules'
  pod 'React-Core/DevSupport', :path => '../node_modules/react-native/'
  pod 'React-RCTActionSheet', :path => '../node_modules/react-native/Libraries/ActionSheetIOS'
  pod 'React-RCTAnimation', :path => '../node_modules/react-native/Libraries/NativeAnimation'
  pod 'React-RCTBlob', :path => '../node_modules/react-native/Libraries/Blob'
  pod 'React-RCTImage', :path => '../node_modules/react-native/Libraries/Image'
  pod 'React-RCTLinking', :path => '../node_modules/react-native/Libraries/LinkingIOS'
  pod 'React-RCTNetwork', :path => '../node_modules/react-native/Libraries/Network'
  pod 'React-RCTSettings', :path => '../node_modules/react-native/Libraries/Settings'
  pod 'React-RCTText', :path => '../node_modules/react-native/Libraries/Text'
  pod 'React-RCTVibration', :path => '../node_modules/react-native/Libraries/Vibration'
  pod 'React-Core/RCTWebSocket', :path => '../node_modules/react-native/'

  pod 'React-cxxreact', :path => '../node_modules/react-native/ReactCommon/cxxreact'
  pod 'React-jsi', :path => '../node_modules/react-native/ReactCommon/jsi'
  pod 'React-jsiexecutor', :path => '../node_modules/react-native/ReactCommon/jsiexecutor'
  pod 'React-jsinspector', :path => '../node_modules/react-native/ReactCommon/jsinspector'
  pod 'React-callinvoker', :path => "../node_modules/react-native/ReactCommon/callinvoker"
  pod 'ReactCommon/turbomodule/core', :path => "../node_modules/react-native/ReactCommon"
  pod 'Yoga', :path => '../node_modules/react-native/ReactCommon/yoga', :modular_headers => true

  pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
  pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'
  # pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'
  pod 'RCT-Folly', :podspec => '../node_modules/react-native/third-party-podspecs/RCT-Folly.podspec'
  pod 'React-perflogger', :path => '../node_modules/react-native/ReactCommon/reactperflogger'
  pod 'React-runtimeexecutor', :path => '../node_modules/react-native/ReactCommon/runtimeexecutor'

  permissions_path = '../node_modules/react-native-permissions/ios'

  pod 'Permission-Camera', :path => "#{permissions_path}/Camera"
  pod 'Permission-Microphone', :path => "#{permissions_path}/Microphone"
  pod 'Permission-Notifications', :path => "#{permissions_path}/Notifications"

  target 'AppTests' do
    inherit! :complete
    # Pods for testing
  end

  use_native_modules!

  # Enables Flipper.
  #
  # Note that if you have use_frameworks! enabled, Flipper will not work and
  # you should disable these next few lines.
  use_flipper!()
  post_install do |installer|
    react_native_post_install(installer)
  end
end

target 'App-tvOS' do
  # Pods for App-tvOS

  target 'App-tvOSTests' do
    inherit! :search_paths
    # Pods for testing
  end
end

AppDelegate.m:

#import "AppDelegate.h"

#if RCT_DEV
#import <React/RCTDevLoadingView.h>
#endif

#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import <Firebase.h>

#import "RNBootSplash.h"

#if DEBUG && TARGET_OS_SIMULATOR
#import <FlipperKit/FlipperClient.h>
#import <FlipperKitLayoutPlugin/FlipperKitLayoutPlugin.h>
#import <FlipperKitUserDefaultsPlugin/FKUserDefaultsPlugin.h>
#import <FlipperKitNetworkPlugin/FlipperKitNetworkPlugin.h>
#import <SKIOSNetworkPlugin/SKIOSNetworkAdapter.h>
#import <FlipperKitReactPlugin/FlipperKitReactPlugin.h>

static void InitializeFlipper(UIApplication *application) {
  FlipperClient *client = [FlipperClient sharedClient];
  SKDescriptorMapper *layoutDescriptorMapper = [[SKDescriptorMapper alloc] initWithDefaults];
  [client addPlugin:[[FlipperKitLayoutPlugin alloc] initWithRootNode:application withDescriptorMapper:layoutDescriptorMapper]];
  [client addPlugin:[[FKUserDefaultsPlugin alloc] initWithSuiteName:nil]];
  [client addPlugin:[FlipperKitReactPlugin new]];
  [client addPlugin:[[FlipperKitNetworkPlugin alloc] initWithNetworkAdapter:[SKIOSNetworkAdapter new]]];
  [client start];
}
#endif

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  if ([FIRApp defaultApp] == nil) {
      [FIRApp configure];
  }
  
#if DEBUG && TARGET_OS_SIMULATOR
  InitializeFlipper(application);
#endif

  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];

#if RCT_DEV
  [bridge moduleForClass:[RCTDevLoadingView class]];
#endif

  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                   moduleName:@"App"
                                            initialProperties:nil];

  if (@available(iOS 13.0, *)) {
      rootView.backgroundColor = [UIColor systemBackgroundColor];
  } else {
      rootView.backgroundColor = [UIColor whiteColor];
  }

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  
  [RNBootSplash initWithStoryboard:@"BootSplash" rootView:rootView];
  
  return YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
  [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
#else
  return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

@end

Android

Click To Expand

Have you converted to AndroidX?

  • [x] my application is an AndroidX application?
  • [x] I am using android/gradle.settings jetifier=true for Android compatibility?
  • [x] I am using the NPM package jetifier for react-native compatibility?

android/build.gradle:

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

buildscript {
    ext {
        buildToolsVersion = "29.0.3"
        minSdkVersion = 21
        compileSdkVersion = 31
        targetSdkVersion = 31
        kotlinVersion = "1.3.72"
        ndkVersion = "20.1.5948944"
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:4.1.0")
        classpath 'com.google.gms:google-services:4.3.10'

        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"

        // 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' }
    }
    // force libs to use recent buildtools
    // https://github.com/luggit/react-native-config/issues/299
    subprojects {
        afterEvaluate {
            project ->
                if (project.hasProperty("android")) {
                    android {
                        compileSdkVersion = 31
                        buildToolsVersion = "29.0.3"
                    }
                }
        }
    }
}

android/app/build.gradle:

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. 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://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 = [
    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 {
    ndkVersion rootProject.ext.ndkVersion

    compileSdkVersion rootProject.ext.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.app.mobileapp"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 117
        versionName "0.4.0"
    }
    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'
        }
        release {
            if (project.hasProperty('MYAPP_UPLOAD_STORE_FILE')) {
                storeFile file(MYAPP_UPLOAD_STORE_FILE)
                storePassword MYAPP_UPLOAD_STORE_PASSWORD
                keyAlias MYAPP_UPLOAD_KEY_ALIAS
                keyPassword MYAPP_UPLOAD_KEY_PASSWORD
            }
        }
    }
    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.release
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }

    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"
    }

    // 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
            // Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc.
            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 =
                        defaultConfig.versionCode * 1000 + versionCodes.get(abi)
            }

        }
    }
}

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

    implementation project(':react-native-set-soft-input-mode')

    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"

    implementation platform('com.google.firebase:firebase-bom:26.6.0')  
    implementation 'com.google.firebase:firebase-core'
    implementation 'com.google.firebase:firebase-messaging'

    /* spongy castle */
    implementation "com.madgag.spongycastle:core:1.58.0.0"
    implementation "com.madgag.spongycastle:prov:1.58.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
    }
}

// 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:

rootProject.name = 'Tauria'
include ':react-native-shared-group-preferences'
project(':react-native-shared-group-preferences').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-shared-group-preferences/android')
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'

include ':react-native-set-soft-input-mode'
project(':react-native-set-soft-input-mode').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-set-soft-input-mode/android')

MainApplication.java:

package com.app.mobileapp;

import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.poppop.RNReactNativeSharedGroupPreferences.RNReactNativeSharedGroupPreferencesPackage;
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.facebook.react.bridge.JSIModulePackage;
import com.swmansion.reanimated.ReanimatedJSIModulePackage;

public class MainApplication extends Application implements ReactApplication {

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

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

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

        @Override
        protected JSIModulePackage getJSIModulePackage() {
          return new ReanimatedJSIModulePackage(); // <- add
        }
      };

  @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.app.mobileapp.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:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.app.mobileapp">
    <supports-screens android:smallScreens="true"
      android:normalScreens="true"       
      android:largeScreens="false"
      android:xlargeScreens="false"/>

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

    <uses-feature android:name="android.hardware.camera" />

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">

    <!-- NotificationService -->
    <service android:name=".MyFirebaseMessagingService"
        android:enabled="true"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

    <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/ic_launcher" />

      <activity
        android:name="com.zoontek.rnbootsplash.RNBootSplashActivity"
        android:theme="@style/BootTheme"
        android:screenOrientation="portrait"
        android:launchMode="singleTask">
        <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|uiMode"
        android:launchMode="singleTask"
        android:exported="true"
        android:windowSoftInputMode="adjustNothing">
      </activity>
    </application>
</manifest>

Environment

Click To Expand

react-native info output:

System:
    OS: macOS 11.1
    CPU: (8) x64 Apple M1
    Memory: 1.05 GB / 16.00 GB
    Shell: 3.2.57 - /bin/bash
  Binaries:
    Node: 14.17.0 - ~/.nvm/versions/node/v14.17.0/bin/node
    Yarn: 1.22.10 - /usr/local/bin/yarn
    npm: 6.14.13 - ~/.nvm/versions/node/v14.17.0/bin/npm
    Watchman: 2021.06.07.00 - /usr/local/bin/watchman
  Managers:
    CocoaPods: 1.11.2 - /Users/rgbedin/.rvm/gems/ruby-3.0.0/bin/pod
  SDKs:
    iOS SDK:
      Platforms: iOS 14.5, DriverKit 20.4, macOS 11.3, tvOS 14.5, watchOS 7.4
    Android SDK:
      API Levels: 23, 25, 26, 27, 28, 29, 30, 31
      Build Tools: 25.0.3, 26.0.2, 27.0.3, 28.0.3, 29.0.2, 29.0.3, 30.0.0, 30.0.1, 30.0.2, 31.0.0
      System Images: android-25 | Google APIs ARM 64 v8a, android-28 | Google Play Intel x86 Atom
      Android NDK: Not Found
  IDEs:
    Android Studio: 2020.3 AI-203.7717.56.2031.7583922
    Xcode: 12.5/12E262 - /usr/bin/xcodebuild
  Languages:
    Java: 11.0.8 - /usr/bin/javac
  npmPackages:
    @react-native-community/cli: Not Found
    react: 17.0.1 => 17.0.1 
    react-native: 0.64.2 => 0.64.2 
    react-native-macos: Not Found
  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:
    • 12.9.0
  • Firebase module(s) you're using that has the issue:
    • Messaging
  • Are you using TypeScript?
    • Y & 3.8.3

rgbedin avatar Oct 06 '21 14:10 rgbedin

Just to give more context; the app is wrapped inside a NotificationProvider that has the following code:

Click To Expand

import React, {
  useEffect,
  useContext,
  FC,
  createContext,
  useRef,
  useState
} from 'react';
import messaging, {
  FirebaseMessagingTypes
} from '@react-native-firebase/messaging';
import { AppAuthModels } from '@developers/App-auth-react-library-core';
import { Platform } from 'react-native';
import {
  checkNotifications,
  requestNotifications,
  RESULTS
} from 'react-native-permissions';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Log } from 'common/helpers/Logger';

// We declare this outside the context because it must run in the headless app (dead state)
// So it cannot be attached to any React component/context
export const startBackgroundNotificationHandler = (): void => {
  messaging().setBackgroundMessageHandler(
    async (
      notification: FirebaseMessagingTypes.RemoteMessage
    ): Promise<void> => {
      Log.log('NotificationContext: background handler:', notification);
      await AsyncStorage.setItem(
        '@App/backgroundNotification',
        JSON.stringify(notification)
      );
    }
  );
};

interface NotificationContextData {
  getDevice: () => Promise<AppAuthModels.AuthDevice | undefined>;
  channelGuidLinking: string | null;
}

export const NotificationContext = createContext({} as NotificationContextData);

export interface NotificationProviderProps {
  onTokenChanged?: (
    device: AppAuthModels.AuthDevice | undefined
  ) => Promise<void>;
}

export const NotificationProvider: FC<
  React.PropsWithChildren<NotificationProviderProps>
> = ({ children, onTokenChanged }) => {
  // Workaround so we can get the latest updated value
  // of this variable inside a callback
  const onTokenChangedRef = useRef(onTokenChanged);
  onTokenChangedRef.current = onTokenChanged;

  const [channelGuidLinking, setChannelGuidLinking] = useState<null | string>(
    null
  );

  const handleNotification = (
    notification: FirebaseMessagingTypes.RemoteMessage
  ): void => {
    Log.log('NotificationContext: handle:', notification.data);
  };

  const attachNotificationCallbacks = (): void => {
    Log.info('NotificationContext: attach notification callbacks');

    messaging().onMessage(
      (notification: FirebaseMessagingTypes.RemoteMessage) => {
        handleNotification(notification);
      }
    );

    messaging().onNotificationOpenedApp(
      (notification: FirebaseMessagingTypes.RemoteMessage) => {
        Log.log('NotificationContext: notification opened app', notification);

        if (notification.data?.channelGuid) {
          setChannelGuidLinking(notification.data?.channelGuid);
        }
      }
    );
  };

  const attachTokenCallbacks = (): void => {
    Log.info('NotificationContext: attach token callbacks');

    messaging().onTokenRefresh(async (token) => {
      Log.info('NotificationContext: token refreshed:', Log.printSecret(token));
      if (onTokenChangedRef.current) {
        const newDevice = await getDevice();
        void onTokenChangedRef.current(newDevice);
      }
    });
  };

  const getDevice = async (): Promise<
    AppAuthModels.AuthDevice | undefined
  > => {
    try {
      const token = await messaging().getToken();
      const type = Platform.OS;

      if (token && (type === 'ios' || type === 'android')) {
        const device = { token, type };
        Log.info('NotificationContext: device:', device);
        return device;
      }
      Log.warn('NotificationContext: could not get device');
      return undefined;
    } catch (e) {
      Log.warn('NotificationContext: error trying to get device token');
      return undefined;
    }
  };

  const handleInitialNotification = async (): Promise<void> => {
    const initialNotification = await messaging().getInitialNotification();
    if (initialNotification) {
      Log.log(
        'NotificationContext: initial notification:',
        initialNotification
      );
    } else {
      Log.log('NotificationContext: *NO* initial notification');
    }
  };

  const handleNotificationsPermission = async (): Promise<void> => {
    const { status } = await checkNotifications();
    Log.info(
      'NotificationContext: notification permission current status:',
      status
    );

    if (status === RESULTS.DENIED) {
      const response = await requestNotifications(['alert', 'badge', 'sound']);
      Log.info('NotificationContext: notification status updated:', response);
    }
  };

  useEffect(() => {
    const init = async () => {
      Log.log('NotificationContext: initing');
      await handleNotificationsPermission();
      attachNotificationCallbacks();
      attachTokenCallbacks();
      await handleInitialNotification();
      Log.log('NotificationContext: inited');
    };

    void init();
  }, []);

  return (
    <NotificationContext.Provider value={{ getDevice, channelGuidLinking }}>
      {children}
    </NotificationContext.Provider>
  );
};

export const useNotification = (): NotificationContextData => {
  const context = useContext(NotificationContext);

  return context;
};

And here's the index.js of the app:

Click To Expand

/* eslint-disable */
import 'react-native-gesture-handler';
import 'web-streams-polyfill/dist/polyfill';
import React from 'react';
import { AppRegistry } from 'react-native';

import { name as appName } from './app.json';

import App from './src/App';
import { EnvironmentContextProvider } from 'contexts/EnvironmentContext';
import {
  startBackgroundNotificationHandler,
  NotificationProvider
} from 'contexts/NotificationContext';
import { NetworkProvider } from 'contexts/NetworkContext';

startBackgroundNotificationHandler();

const HeadlessCheck = ({ isHeadless }) => {
  if (isHeadless) {
    return null;
  }

  return (
    <EnvironmentContextProvider>
      <NotificationProvider>
        <NetworkProvider>
          <App />
        </NetworkProvider>
      </NotificationProvider>
    </EnvironmentContextProvider>
  );
};

AppRegistry.registerComponent(appName, () => HeadlessCheck);

rgbedin avatar Oct 06 '21 14:10 rgbedin

did you resolve this ? any solution ?

dgomez-orangeloops avatar Oct 22 '21 15:10 dgomez-orangeloops

No resolutions or workarounds found yet.

rgbedin avatar Oct 24 '21 21:10 rgbedin

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.

stale[bot] avatar Apr 18 '22 18:04 stale[bot]

I have the same issue still with versions 14.11.1

I use Notifee also for data messages and i noticed that when i swipe up the app and get a notification i get a DELIVERY event onBackground handler and when i click on it i get an event of PRESS onForeground... Still when i get a notification created directly from Firebase the onNotificationOpenedApp() does not work

alelaru avatar Oct 24 '22 10:10 alelaru

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.

github-actions[bot] avatar Dec 05 '22 19:12 github-actions[bot]