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

response from onNotification not same with response onNotificationOpened

Open Heru6664 opened this issue 7 years ago • 3 comments

Issue

I have issue with my notification. i create listener notification, and i create function to handle open notification. but the response from listener notification is different with response from onNotificationOpened. so i can't do next process after i click notification because the payload what i got from notification listener before is missing after i click this notification.

Project Files

so this is my listener notification , which is to receive new notification and show notification.

this.notificationListener = firebase
      .notifications()
      .onNotification(notifications => {
        const { title, body, notificationId } = notifications;
        console.log("notif", notifications);

          const localNotification = new firebase.notifications.Notification({
            sound: "default",
            show_in_foreground: true,
            show_in_background: true
          })
            .setNotificationId(notificationId)
            .setTitle(title)
            .setBody(body)
            .android.setChannelId("test-channel")
            .android.setSmallIcon("ic_notif")
            .android.setPriority(firebase.notifications.Android.Priority.High)
            .android.setAutoCancel(true)
            .android.setVisibility(
              firebase.notifications.Android.Visibility.Public
            );

          firebase.notifications().displayNotification(localNotification);
        

and this is the log after i get new notification. as you can see below, there was the data in key _data. (order_id, etc)

image

this is my function for handling action after i click the notification

        firebase.notifications().onNotificationOpened(notificationOpen => {
          const { title, body, order_id } = notificationOpen.notification;
          const id = order_id;
          console.log("openNotif", notificationOpen);

          this.props.navigation.navigate("DetailOrder", {
            id,
            onNavigateBack: () => this.refresh(),
            status: "notif"
          });
        });

and this is my log after i click that notification. you can see below that the data before is gone. so i can't do next process for those order_id image

iOS

ios/Podfile:

  • [ ] I'm not using Pods
  • [] I'm using Pods and my Podfile looks like:
# N/A

AppDelegate.m:

// N/A

Android

android/build.gradle:

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

buildscript {
    ext {
        buildToolsVersion = "27.0.3"
        minSdkVersion = 16
        compileSdkVersion = 27
        targetSdkVersion = 27
        supportLibVersion = "27.1.1"
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.0'
        classpath 'com.google.gms:google-services:4.0.1'
        classpath 'com.android.tools.build:gradle:2.2.3'
        
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        google()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        maven { url 'https://maven.google.com' }
        maven { url "https://jitpack.io" }
    }
}


task wrapper(type: Wrapper) {
    gradleVersion = '4.4'
    distributionUrl = distributionUrl.replace("bin", "all")
}

android/app/build.gradle:

apply plugin: "com.android.application"

import com.android.build.OutputFile

/**
 * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
 * and bundleReleaseJsAndAssets).
 * These basically call `react-native bundle` with the correct arguments during the Android build
 * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
 * bundle directly from the development server. Below you can see all the possible configurations
 * and their defaults. If you decide to add a configuration block, make sure to add it before the
 * `apply from: "../../node_modules/react-native/react.gradle"` line.
 *
 * project.ext.react = [
 *   // the name of the generated asset file containing your JS bundle
 *   bundleAssetName: "index.android.bundle",
 *
 *   // the entry file for bundle generation
 *   entryFile: "index.android.js",
 *
 *   // whether to bundle JS and assets in debug mode
 *   bundleInDebug: false,
 *
 *   // whether to bundle JS and assets in release mode
 *   bundleInRelease: true,
 *
 *   // whether to bundle JS and assets in another build variant (if configured).
 *   // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
 *   // The configuration property can be in the following formats
 *   //         'bundleIn${productFlavor}${buildType}'
 *   //         'bundleIn${buildType}'
 *   // bundleInFreeDebug: true,
 *   // bundleInPaidRelease: true,
 *   // bundleInBeta: true,
 *
 *   // whether to disable dev mode in custom build variants (by default only disabled in release)
 *   // for example: to disable dev mode in the staging build type (if configured)
 *   devDisabledInStaging: true,
 *   // The configuration property can be in the following formats
 *   //         'devDisabledIn${productFlavor}${buildType}'
 *   //         'devDisabledIn${buildType}'
 *
 *   // the root of your project, i.e. where "package.json" lives
 *   root: "../../",
 *
 *   // where to put the JS bundle asset in debug mode
 *   jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
 *
 *   // where to put the JS bundle asset in release mode
 *   jsBundleDirRelease: "$buildDir/intermediates/assets/release",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in debug mode
 *   resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in release mode
 *   resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
 *
 *   // by default the gradle tasks are skipped if none of the JS files or assets change; this means
 *   // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
 *   // date; if you have any other folders that you want to ignore for performance reasons (gradle
 *   // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
 *   // for example, you might want to remove it from here.
 *   inputExcludes: ["android/**", "ios/**"],
 *
 *   // override which node gets called and with what additional arguments
 *   nodeExecutableAndArgs: ["node"],
 *
 *   // supply additional arguments to the packager
 *   extraPackagerArgs: []
 * ]
 */

project.ext.react = [
    entryFile: "index.js"
]

apply from: "../../node_modules/react-native/react.gradle"

/**
 * Set this to true to create two separate APKs instead of one:
 *   - An APK that only works on ARM devices
 *   - An APK that only works on x86 devices
 * The advantage is the size of the APK is reduced by about 4MB.
 * Upload all the APKs to the Play Store and people will download
 * the correct one based on the CPU architecture of their device.
 */
def enableSeparateBuildPerCPUArchitecture = false

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = false

android {
    compileSdkVersion rootProject.ext.compileSdkVersion
    buildToolsVersion rootProject.ext.buildToolsVersion

    defaultConfig {
        applicationId "com.abuexpress"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        vectorDrawables.useSupportLibrary = true
        versionCode 1
        versionName "1.0.1"
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    implementation project(':react-native-image-crop-picker')
    implementation project(':react-native-device-info')
    implementation project(':react-native-gesture-handler')
    implementation project(':react-native-firebase')
    implementation 'me.leolin:ShortcutBadger:1.1.21@aar'
    implementation 'com.google.firebase:firebase-core:16.0.1'
    implementation 'me.leolin:ShortcutBadger:1.1.21@aar'
    implementation "com.google.firebase:firebase-messaging:17.3.4"
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.google.android.gms:play-services-base:16.0.1"
    implementation "com.google.firebase:firebase-core:16.0.6"
    implementation "com.facebook.react:react-native:+"  // From node_modules
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true
apply plugin: 'com.google.gms.google-services'

android/settings.gradle:

rootProject.name = 'abuExpress'
include ':react-native-image-crop-picker'
project(':react-native-image-crop-picker').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-image-crop-picker/android')
include ':react-native-device-info'
project(':react-native-device-info').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-device-info/android')
include ':react-native-firebase'
project(':react-native-firebase').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-firebase/android')
include ':react-native-gesture-handler'
project(':react-native-gesture-handler').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-gesture-handler/android')

include ':app'

MainApplication.java:

package com.abuexpress;

import android.app.Application;

import com.facebook.react.ReactApplication;
import com.reactnative.ivpusic.imagepicker.PickerPackage;
import com.learnium.RNDeviceInfo.RNDeviceInfo;
import io.invertase.firebase.RNFirebasePackage;
import io.invertase.firebase.messaging.RNFirebaseMessagingPackage;
import io.invertase.firebase.notifications.RNFirebaseNotificationsPackage;
import com.swmansion.gesturehandler.react.RNGestureHandlerPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;

import java.util.Arrays;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {

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

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
            new PickerPackage(),
            new RNDeviceInfo(),
            new RNFirebasePackage(),
            new RNFirebaseMessagingPackage(),
            new RNFirebaseNotificationsPackage(),
            new RNGestureHandlerPackage()
      );
    }

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

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
  }
}

AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.abuexpress">
 
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-feature android:name="android.hardware.camera" android:required="false" />
    <uses-feature android:name="android.hardware.camera.front" android:required="false" />
 
    <application
     android:name=".MainApplication"
     android:label="@string/app_name"
     android:icon="@mipmap/ic_launcher"
     android:allowBackup="false"
     android:launchMode="singleTop"
     android:theme="@style/AppTheme">
    <meta-data
     android:name="com.google.firebase.messaging.default_notification_channel_id"
     android:value="@string/default_notification_channel_id"/>
    
    <receiver android:name="io.invertase.firebase.notifications.RNFirebaseBackgroundNotificationActionReceiver" android:exported="true">
      <intent-filter>
        <action android:name="io.invertase.firebase.notifications.BackgroundAction"/>
      </intent-filter>
    </receiver>
    <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
      <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
      </intent-filter>
    </service>
    <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />

    <meta-data
      android:name="com.google.firebase.messaging.default_notification_icon"
      android:resource="@mipmap/ic_notif" /> 
 
      <receiver android:name="io.invertase.firebase.notifications.RNFirebaseNotificationReceiver"/>
      <receiver android:enabled="true" android:exported="true"  android:name="io.invertase.firebase.notifications.RNFirebaseNotificationsRebootReceiver">
        <intent-filter>
          <action android:name="android.intent.action.BOOT_COMPLETED"/>
          <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
          <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
          <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
      </receiver>
 
      <activity
       android:name=".MainActivity"
       android:label="@string/app_name"
       android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
       android:windowSoftInputMode="adjustResize">
        <intent-filter>
          <action android:name="android.intent.action.MAIN" />
          <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
    </application>
 
</manifest>

Environment

  • 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
  • If known, the version of the platform are you experiencing the issue on:
    • ADD_SOMETHING_HERE e.g. iOS 10 or Android API 28
  • Operating System:
    • [x ] MacOS, version: N/A
    • [ ] Windows, version: N/A
    • [ ] Other, please specify: N/A
  • Build Tools:
    • ADD_SOMETHING_HERE e.g. Xcode 10, Android Studio 3.2
  • React Native version:
    • 0.57.7
  • React Native Firebase library version:
    • 5.2.1
  • Firebase module(s) you're using that has the issue:
    • [x] N/A
    • [ ] Authentication
    • [ ] Analytics
    • [ ] Cloud Firestore
    • [ ] Cloud Messaging (FCM)
    • [ ] Crashlytics
    • [ ] Dynamic Links
    • [ ] Functions Callable
    • [ ] In App Messaging
    • [ ] Indexing
    • [ ] Invites
    • [ ] Instance ID
    • [ ] ML Kit
    • [x] Notifications
    • [ ] Performance Monitoring
    • [ ] Realtime Database
    • [ ] Remote Config
    • [ ] Storage
  • Are you using TypeScript?
    • [x] No
    • [ ] Yes, version: N/A
  • Are you using Expo, e.g. ExpoKit?
    • [x] No
    • [ ] Yes, I've not ejected
    • [ ] Yes, but I have ejected to ExpoKit
    • [ ] Yes, but I have ejected to vanilla React Native
    • Expo version: N/A

Think react-native-firebase is great? Please consider supporting the project with any of the below:

Heru6664 avatar Mar 28 '19 05:03 Heru6664

I am facing the same issues when working on our project. I have done some research with my friend (android and IOS). These are the result :

  • Application in foreground ==> get the notification, click notification ==> data field is gone
  • Application in background ==> get the notification, click notification ==> data is still available

Anyone can help us? Thanks

fajarainul avatar Mar 28 '19 08:03 fajarainul

You have to property "setData()" while creating the local notification similar to setBody. Then it will be available in the onNotificationOpened.

eg: .setNotificationId(notificationId) .setTitle(title) .setBody(body) .setData(data) // <-- This method

sapdey avatar Mar 28 '19 20:03 sapdey

Great! Now it is working properly. Thank you @sapdey !

fajarainul avatar Mar 29 '19 02:03 fajarainul