Skip to content
This repository was archived by the owner on Jan 14, 2025. It is now read-only.

onNotification not running for a remote notification #2017

Open
Ruzen1 opened this issue May 18, 2021 · 18 comments
Open

onNotification not running for a remote notification #2017

Ruzen1 opened this issue May 18, 2021 · 18 comments

Comments

@Ruzen1
Copy link

Ruzen1 commented May 18, 2021

Question

Hey I am trying to get the onNotification to run from a remote notification. However I am not being able to get the onNotification to run. Could you suggest me? I have checked the example but it only contains the localNotification codes right? Can you please guide me to a remote notification example?

React native version : 0.61.3
"react-native-push-notification": "^3.5.2",

Here are my codes.

index.js

import {AppRegistry} from 'react-native'
import App from './src/App'
import {name as appName} from './app.json'
import BackgroundGeolocation from 'react-native-background-geolocation'
import PassingBooksProcessor from './src/services/passingBooksProcessorService'

AppRegistry.registerComponent(appName, () => App)

import PushNotificationIOS from '@react-native-community/push-notification-ios'
import PushNotification from 'react-native-push-notification'

// Must be outside of any component LifeCycle (such as `componentDidMount`).
PushNotification.configure({
   // (optional) Called when Token is generated (iOS and Android)
   onRegister: function(token) {
       console.log('TOKEN:', token)
   },

   // (required) Called when a remote is received or opened, or local notification is opened
   onNotification: function(notification) {
       console.log('NOTIFICATION:', notification)

       // process the notification

       // (required) Called when a remote is received or opened, or local notification is opened
       notification.finish(PushNotificationIOS.FetchResult.NoData)
   },

   // (optional) Called when Registered Action is pressed and invokeApp is false, if true onNotification will be called (Android)
   onAction: function(notification) {
       console.log('ACTION:', notification.action)
       console.log('NOTIFICATION:', notification)

       // process the action
   },

   // (optional) Called when the user fails to register for remote notifications. Typically occurs when APNS is having issues, or the device is a simulator. (iOS)
   onRegistrationError: function(err) {
       console.error(err.message, err)
   },

   // IOS ONLY (optional): default: all - Permissions to register.
   permissions: {
       alert: true,
       badge: true,
       sound: true,
   },

   // Should the initial notification be popped automatically
   // default: true
   popInitialNotification: true,

   /**
    * (optional) default: true
    * - Specified if permissions (ios) and token (android and ios) will requested or not,
    * - if not, you must call PushNotificationsHandler.requestPermissions() later
    * - if you are not using remote notification or do not have Firebase installed, use this:
    *     requestPermissions: Platform.OS === 'ios'
    */
   requestPermissions: true,
})


MainApplication.java

package com.taknal.app.dev;

import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import co.apptailor.googlesignin.RNGoogleSigninPackage;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import com.reactnativecommunity.netinfo.NetInfoPackage;
import com.dieam.reactnativepushnotification.ReactNativePushNotificationPackage;  // <--- Import Package

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 BuildConfigPackage());
         packages.add(new ReactNativePushNotificationPackage()) // <---- Add the Package
         // packages.add(new NetInfoPackage());
         return packages;
       }

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

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

 @Override
 public void onCreate() {
   super.onCreate();
   SoLoader.init(this, /* native exopackage */ false);
   initializeFlipper(this); // Remove this line if you don't want Flipper enabled
 }

 /**
  * Loads Flipper in React Native templates.
  *
  * @param context
  */
 private static void initializeFlipper(Context context) {
   if (BuildConfig.DEBUG) {
     try {
       /*
        We use reflection here to pick up the class that initializes Flipper,
       since Flipper library is not available in release mode
       */
       Class<?> aClass = Class.forName("com.facebook.flipper.ReactNativeFlipper");
       aClass.getMethod("initializeFlipper", Context.class).invoke(null, context);
     } catch (ClassNotFoundException e) {
       e.printStackTrace();
     } catch (NoSuchMethodException e) {
       e.printStackTrace();
     } catch (IllegalAccessException e) {
       e.printStackTrace();
     } catch (InvocationTargetException e) {
       e.printStackTrace();
     }
   }
 }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools">

   <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

   <uses-permission android:name="android.permission.WAKE_LOCK" />
   <permission
       android:name="${applicationId}.permission.C2D_MESSAGE"
       android:protectionLevel="signature" />
   <uses-permission android:name="${applicationId}.permission.C2D_MESSAGE" />
   <uses-permission android:name="android.permission.VIBRATE" />
   <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

   <application>
       <receiver
           android:name="com.google.android.gms.gcm.GcmReceiver"
           android:exported="true"
           android:permission="com.google.android.c2dm.permission.SEND" >
           <intent-filter>
               <action android:name="com.google.android.c2dm.intent.RECEIVE" />
               <category android:name="${applicationId}" />
           </intent-filter>
       </receiver>
       
       <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
       <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
           <intent-filter>
               <action android:name="android.intent.action.BOOT_COMPLETED" />
           </intent-filter>
       </receiver>
       <service android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationRegistrationService"/>
       <service
           android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService"
           android:exported="false" >
           <intent-filter>
               <action android:name="com.google.android.c2dm.intent.RECEIVE" />
           </intent-filter>
       </service>

   <application android:usesCleartextTraffic="true" tools:targetApi="28" tools:ignore="GoogleAppIndexingWarning" />
</manifest>

build.gradle

apply plugin: "com.android.application"
apply plugin: 'io.fabric'

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",
   enableHermes: false,  // clean and rebuild if changing
]

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

Project background_geolocation = project(':react-native-background-geolocation')
apply from: "${background_geolocation.projectDir}/app.gradle"

def useIntlJsc = false

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

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

/**
* The preferred build flavor of JavaScriptCore.
*
* For example, to use the international variant, you can use:
* `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
*
* The international variant includes ICU i18n library and necessary data
* allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
* give correct results when using with locales other than en-US.  Note that
* this variant is about 6MiB larger per architecture than default.
*/
def jscFlavor = 'org.webkit:android-jsc:+'

/**
* Whether to enable the Hermes VM.
*
* This should be set on project.ext.react and mirrored here.  If it is not set
* on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
* and the benefits of using Hermes will therefore be sharply reduced.
*/
def enableHermes = project.ext.react.get("enableHermes", false);

android {
   compileSdkVersion rootProject.ext.compileSdkVersion

   compileOptions {
       sourceCompatibility JavaVersion.VERSION_1_8
       targetCompatibility JavaVersion.VERSION_1_8
   }

   defaultConfig {
       applicationId "com.taknal.app.dev"
       minSdkVersion rootProject.ext.minSdkVersion
       targetSdkVersion rootProject.ext.targetSdkVersion
       versionCode 1
       versionName "1.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_RELEASE_STORE_FILE')) {
               storeFile file(MYAPP_RELEASE_STORE_FILE)
               storePassword MYAPP_RELEASE_STORE_PASSWORD
               keyAlias MYAPP_RELEASE_KEY_ALIAS
               keyPassword MYAPP_RELEASE_KEY_PASSWORD
           }
       }
   }
   flavorDimensions "env"
   productFlavors {
       dev {
           dimension "env"
           applicationId "com.taknal.app.dev"
           buildConfigField "String", "ENV", "\"dev\""
       }
       prd {
           dimension "env"
           applicationId "com.taknal.app.dev"
           buildConfigField "String", "ENV", "\"prd\""
       }
   }
   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"
           // Add following proguardFiles (leave existing one above untouched)
           // proguardFiles "${background_geolocation.projectDir}/proguard-rules.pro"
       }
   }
   // applicationVariants are e.g. debug, release
   applicationVariants.all { variant ->
       variant.outputs.each { output ->
           // For each separate APK per architecture, set a unique version code as described here:
           // https://developer.android.com/studio/build/configure-apk-splits.html
           def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
           def abi = output.getFilter(OutputFile.ABI)
           if (abi != null) {  // null for the universal-debug, universal-release variants
               output.versionCodeOverride =
                       versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
           }

       }
   }
   dexOptions {
       javaMaxHeapSize "4g"
   }
}

dependencies {
   implementation project(':react-native-android-open-settings')
   compile project(':react-native-push-notification')
   compile ('com.google.android.gms:play-services-gcm:8.1.0') {
       force = true;
   }
   implementation project(':react-native-device-info')
   implementation project(':react-native-gesture-handler')
   // implementation project(':react-native-firebase')
   // implementation project(':@react-native-community_netinfo')
   implementation fileTree(dir: "libs", include: ["*.jar"])
   implementation "com.facebook.react:react-native:+"  // From node_modules
   implementation 'com.google.firebase:firebase-analytics:17.2.0'
   compile 'com.facebook.android:facebook-android-sdk:[4,5)'
   implementation 'com.android.support:support-annotations:28.0.0'
   implementation project(':react-native-community-netinfo')
   implementation "com.google.firebase:firebase-messaging:21.1.0"

   if (enableHermes) {
       def hermesPath = "../../node_modules/hermes-engine/android/";
       debugImplementation files(hermesPath + "hermes-debug.aar")
       releaseImplementation files(hermesPath + "hermes-release.aar")
   } else {
       implementation jscFlavor
   }

   if (useIntlJsc) {
       implementation 'org.webkit:android-jsc-intl:+'
   } else {
       implementation 'org.webkit:android-jsc:+'
   }
}

// 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)
apply plugin: 'com.google.gms.google-services'
@Dallas62
Copy link
Collaborator

Hi,
When do you want to call onNotification ? On app open ? When a remote notification arrives ?
What is the payload of your remote notification ?
All information exist in issues history.
Regards

@abhideepmallick
Copy link

Here is my notification service class:

import { Platform } from 'react-native';
import PushNotificationIOS from '@react-native-community/push-notification-ios';
import PushNotification from 'react-native-push-notification';

import emitter from 'tiny-emitter/instance';

import { ANDROID_SENDER_ID } from '../../shared/settings/Constants';

import processNotification from '../helpers/PushNotificationHelper';


let hasStarted = false;
let pushToken = null;
let badgeNumber = 0;

export const getPushToken = () => pushToken;
export const getBadgeNumber = () => badgeNumber;

export const startNotifications = () => {
  PushNotification.configure({
    onRegister: (token) => {
      if (hasStarted) return;

      console.log('TOKEN:', token);
      pushToken = token;
      emitter.emit('push-notification-token-updated', token);
      hasStarted = true;
    },
    onNotification: (notification) => {
      console.log('notification: ', notification);
      // Normalise the notification across iOS and Android
      if (!notification) return;

      // TODO: this processing might be incomplete....
      // TODO: URL decode on the text?
      const notificationData = processNotification(Platform.OS, notification);
      console.log('notificationData: ', notificationData);

      emitter.emit('push-notification-received', notificationData);

      if (notification.badge) {
        badgeNumber = notification.badge;
        console.log('badgeNumber: ', badgeNumber);
        emitter.emit('push-notification-badge-changed', badgeNumber);
        PushNotification.setApplicationIconBadgeNumber(badgeNumber);
      }


      // Avoid being throttled on iOS by notifying the system that
      // we're done with a notification
      if (Platform.OS === 'ios'
            && notification
            && notification.finish
            && typeof notification.finish === 'function'
      ) {
        if (
          notification
              && PushNotificationIOS
              && PushNotificationIOS.FetchResult
              && PushNotificationIOS.FetchResult.NoData
        ) {
          notification.finish(PushNotificationIOS.FetchResult.NoData);
        }
      }
    },
    senderID: ANDROID_SENDER_ID,
    popInitialNotification: false,
    requestPermissions: true,
  });
};

I call the startNotifications(); function from app.js file. I am successfully getting the console.log('TOKEN:', token); log but not the console.log('notification: ', notification); log when the notification is supposed to be received. This problem exists in both iOS and Android platforms and we have checked our push notifications server to confirm that it is sending the notifications successfully.

I am using react-native-push-notification version 7.3.1.

@Dallas62
Copy link
Collaborator

Can you share the remote notification payload, without it I can't help.

@abhideepmallick
Copy link

Yep

@abhideepmallick
Copy link

abhideepmallick commented May 19, 2021

{
    "uuid":"XXXX-XXX-XX-XXXX-XXXXXXXXXX",
    "displayName":"App\\Jobs\\SendPush",
    "job":"Illuminate\\Queue\\CallQueuedHandler@call","maxTries":3,"maxExceptions":null,"delay":null,"timeout":null,"timeoutAt":null,
    "data":{
        "commandName":"App\\Jobs\\SendPush",
        "command":"O:17:\"App\\Jobs\\SendPush\":15:{s:5:\"tries\";i:3;s:9:\"\u0000*\u0000toUser\";O:45:\"Illuminate\\Contracts\\Database\\ModelIdentifier\":4:{s:5:\"class\";s:15:\"App\\Models\\User\";s:2:\"id\";i:4907;s:9:\"relations\";a:0:{}s:10:\"connection\";s:5:\"pgsql\";}s:10:\"\u0000*\u0000subject\";s:30:\"Subscription payment succeeded\";s:10:\"\u0000*\u0000message\";s:125:\"Hi Darwin,\n\nLazaro has been successfully charged for their parking subscription at XYZ Street, XYZ.\n\nwww.xyz.com\n\";s:10:\"\u0000*\u0000trigger\";O:45:\"Illuminate\\Contracts\\Database\\ModelIdentifier\":4:{s:5:\"class\";s:23:\"App\\Models\\Subscription\";s:2:\"id\";i:1259;s:9:\"relations\";a:9:{i:0;s:3:\"bay\";i:1;s:8:\"bay.park\";i:2;s:14:\"bay.park.state\";i:3;s:20:\"bay.park.state.taxes\";i:4;s:13:\"bay.park.user\";i:5;s:5:\"space\";i:6;s:11:\"space.state\";i:7;s:9:\"requestor\";i:8;s:14:\"requestor.user\";}s:10:\"connection\";s:5:\"pgsql\";}s:11:\"\u0000*\u0000category\";s:28:\"subscriptionPaymentSucceeded\";s:13:\"\u0000*\u0000pushStatus\";i:0;s:3:\"job\";N;s:10:\"connection\";N;s:5:\"queue\";N;s:15:\"chainConnection\";N;s:10:\"chainQueue\";N;s:5:\"delay\";N;s:10:\"middleware\";a:0:{}s:7:\"chained\";a:0:{}}"}}

@Dallas62 here is the payload

@Dallas62
Copy link
Collaborator

The payload doesn't seems to be a valid Firebase or APN payload.
If you are using another provider you should contact this provider.

@abhideepmallick
Copy link

abhideepmallick commented May 19, 2021

This is the payload sent via AWS to the device. @Dallas62 we can't yet log anything on the front end as onNotification isn't firing and the log isn't showing up.

Full version:

{
	"default": "Great news, Anthony!\n\nYour booking of No 39 Soi Suanplu,  for 1 day was successful.",
	"APNS_SANDBOX": "{\"aps\":{\"alert\":{\"title\":\"Booking successful\",\"body\":\"Great news, Anthony!Your booking of No 39 Soi Suanplu, for 1 day was successful.\\n\"},\"badge\":0,\"sound\":\"default\",\"category\":\"bookingApproved\"},\"object_id\":1567,\"message_category\":\"bookingApproved\"}",
	"APNS": "{\"aps\":{\"alert\":{\"title\":\"Booking successful\",\"body\":\"Great news, Anthony!Your booking of No 39 Soi Suanplu, for 1 day was successful.\\n\"},\"badge\":0,\"sound\":\"default\",\"category\":\"bookingApproved\"},\"object_id\":1567,\"message_category\":\"bookingApproved\"}",
	"GCM": "{\"notification\":{\"body\":\"Great news, Anthony!Your booking of No 39 Soi Suanplu,  for 1 day was successful.\\n\",\"title\":\"Booking successful\",\"icon\":\"ic_notification\"},\"data\":{\"body\":\"Great news, Anthony!Your booking of No 39 Soi Suanplu, for 1 day was successful.\\n\",\"title\":\"Booking successful\",\"object_id\":1567,\"message_category\":\"bookingApproved\",\"badge\":0,\"largeIcon\":\"ic_notification\",\"smallIcon\":\"ic_notification\"},\"priority\":\"high\"}"
}

@ricbermo
Copy link

I'm having the same issue, the only difference is that I'm sending some test notifications using FBC.
Relevant code:

export const configure = () => {
  PushNotification.configure({
    onRegister: function ({token}) {
      console.log(token);
    },

    onNotification: function (notification) {
      console.log('NOTIFICATION:', notification);
      notification.finish(PushNotificationIOS.FetchResult.NoData);
    },

    onAction: function (notification) {
      console.log('ACTION:', notification.action);
      console.log('NOTIFICATION:', notification);
    },

    onRegistrationError: function (err) {
      console.error(err.message, err);
    },

    permissions: {
      alert: true,
      badge: true,
      sound: true,
    },

    popInitialNotification: true,
    requestPermissions: true,
  });
};

and then, in index.js

import {configure} from './src/helpers/notifications';
....
configure();
....
AppRegistry.registerComponent(appName, () => App);

The token is printed and but no notifications are displayed. Maybe FB is down?
I double-checked the google-services file which is placed in android/app/google-services.

Thanks in advance.

@Dallas62
Copy link
Collaborator

Dallas62 commented May 19, 2021

There is multiple kind of notifications, do not mix concept. Firebase Console will never trigger onNotification in background, it's sending notification-only.

To trigger onNotification in background you must send a data-only notification:
APNS:
https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html
Configuring a Background Update Notification

Firebase:
https://firebase.google.com/docs/cloud-messaging/concept-options

There is already many closed issues about this kind of issue and a TROUBLESHOOTING file.

@abhideepmallick
Copy link

There is multiple kind of notifications, do not mix concept. Firebase Console will never trigger onNotification in background, it's sending notification-only.

To trigger onNotification in background you must send a data-only notification:
APNS:
https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html
Configuring a Background Update Notification

Firebase:
https://firebase.google.com/docs/cloud-messaging/concept-options

There is already many closed issues about this kind of issue and a TROUBLESHOOTING file.

@Dallas62 I have added the full version of the payload as well for your reference here #2017 (comment)

@Dallas62
Copy link
Collaborator

This is the payload sent via AWS to the device. @Dallas62 we can't yet log anything on the front end as onNotification isn't firing and the log isn't showing up.

Full version:

{
	"default": "Great news, Anthony!\n\nYour booking of No 39 Soi Suanplu,  for 1 day was successful.",
	"APNS_SANDBOX": "{\"aps\":{\"alert\":{\"title\":\"Booking successful\",\"body\":\"Great news, Anthony!Your booking of No 39 Soi Suanplu, for 1 day was successful.\\n\"},\"badge\":0,\"sound\":\"default\",\"category\":\"bookingApproved\"},\"object_id\":1567,\"message_category\":\"bookingApproved\"}",
	"APNS": "{\"aps\":{\"alert\":{\"title\":\"Booking successful\",\"body\":\"Great news, Anthony!Your booking of No 39 Soi Suanplu, for 1 day was successful.\\n\"},\"badge\":0,\"sound\":\"default\",\"category\":\"bookingApproved\"},\"object_id\":1567,\"message_category\":\"bookingApproved\"}",
	"GCM": "{\"notification\":{\"body\":\"Great news, Anthony!Your booking of No 39 Soi Suanplu,  for 1 day was successful.\\n\",\"title\":\"Booking successful\",\"icon\":\"ic_notification\"},\"data\":{\"body\":\"Great news, Anthony!Your booking of No 39 Soi Suanplu, for 1 day was successful.\\n\",\"title\":\"Booking successful\",\"object_id\":1567,\"message_category\":\"bookingApproved\",\"badge\":0,\"largeIcon\":\"ic_notification\",\"smallIcon\":\"ic_notification\"},\"priority\":\"high\"}"
}

@abhideepmallick Both payload are for notification-only, they will not trigger onNotification until the notification is pressed. You must send a data-only notification to trigger onNotification in background. Refer to links provided.

@ignaciosantise
Copy link

Same issue in Android. Here's my case

  1. A remote notification arrives
  2. onNotification is executed correctly. (data, title and message arrive OK)
  3. User presses the notification
  4. onNotification doesn't get executed (neither if the app is in foreground or background)

Notification structure

{
    "data": {
        ....
    },
    "notification": {
        "title": "Test title",
        "body": "Test body"
    }
}

Environment

"react-native": "0.63.4",
"react-native-push-notification": "7.3.1"

@Dallas62
Copy link
Collaborator

Same issue in Android. Here's my case

  1. A remote notification arrives
  2. onNotification is executed correctly. (data, title and message arrive OK)
  3. User presses the notification
  4. onNotification doesn't get executed (neither if the app is in foreground or background)

Notification structure

{
    "data": {
        ....
    },
    "notification": {
        "title": "Test title",
        "body": "Test body"
    }
}

Environment

"react-native": "0.63.4",
"react-native-push-notification": "7.3.1"

@ignaciosantise It's not the same issue. You can look into the Readme:

If your app has an @OverRide on onNewIntent in MainActivity.java ensure that function includes a super call on onNewIntent > (if your MainActivity.java does not have an @OverRide for onNewIntent skip this):

    @Override
    public void onNewIntent(Intent intent) {
        ...
        super.onNewIntent(intent);
        ...
    }

Or search in issue history for "splashscreen".

@ignaciosantise
Copy link

Thanks @Dallas62 for your help. It was an issue with the splashscreen. This comment helped me #1592 (comment)

@compelling
Copy link

Also had the problem that onNotification was not fired for a remote notification on Android. The Installation section says

NOTE: For Android, you will still have to manually update the AndroidManifest.xml (as below) in order to use Scheduled Notifications.

We were only using remote notification, not scheduled ones, but adding the extra lines to AndroidManifest.xml did the trick for us. Spent lots of time on this issue, but finally started to try the various manual installations options which was how i found this out.

@schlafnie
Copy link

@compelling which lines did you add to make remote notifications for Android work? We are experiencing the same issue with external service notifications

@compelling
Copy link

@schlafnie In your android/app/src/main/AndroidManifest.xml make sure this exists:

.....
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

<application ....>
    <!-- Change the value to true to enable pop-up for in foreground on receiving remote notifications (for prevent duplicating while showing local notifications set this to false) -->
    <meta-data  android:name="com.dieam.reactnativepushnotification.notification_foreground"
                android:value="false"/>
    <!-- Change the resource name to your App's accent color - or any other color you want -->
    <meta-data  android:name="com.dieam.reactnativepushnotification.notification_color"
                android:resource="@color/white"/> <!-- or @android:color/{name} to use a standard color -->

    <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationActions" />
    <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
    <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
        <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"/>
        </intent-filter>
    </receiver>

    <service
        android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService"
        android:exported="false" >
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
 .....

@Ajmal0197
Copy link

Ajmal0197 commented Jul 15, 2021

If are using splash screen then in android you may get the issue of onNotification not getting called:

Solution:

AndroidManifest.xml

      <activity
      android:name=".SplashActivity"
      android:theme="@style/SplashTheme"
      android:label="@string/app_name">
      <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:windowSoftInputMode="adjustResize"
        android:exported="true">

MainActivity.java

    // Add this method.
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        SplashScreen.show(this);
        super.onCreate(savedInstanceState);
    }

SplashActivity.java

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = new Intent(this, MainActivity.class);

        // Pass along FCM messages/notifications etc.
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            intent.putExtras(extras);
        }

        startActivity(intent);
        finish();
    }

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

8 participants