react-native-push-notification icon indicating copy to clipboard operation
react-native-push-notification copied to clipboard

onNotification is not called when remote notification arrives and app is in background/foreground

Open alex-mironov opened this issue 4 years ago • 23 comments

I'm to update the UI when onNotification arrives. In general onNotification works as expected when app is killed. It wakes up -> onNotification gets called.

BUT onNotification doesn't seem to be getting called when the app is NOT killed, i.e. in foreground or background.

I saw people reporting similar issues for local notifs, but I assume for remote notifications it's different?

Can someone suggest what could be wrong?

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

const Root = () => {
  PushNotification.configure({
    onRegister: pushToken => {
      console.log(pushToken.token)
    },

    onNotification: notification => {
      console.log('Notification received', notification)
      notification.finish(PushNotificationIOS.FetchResult.NoData)
    },
    onError: err => {
      console.log('Error configuring notifications', err)
    },

    senderID: SENDER_ID,

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

    popInitialNotification: true,
    requestPermissions: Platform.OS === 'android',
  })

  return <Router />
}

The library version:

    "react-native-push-notification": "^3.5.0",

alex-mironov avatar May 22 '20 15:05 alex-mironov

Hi @alex-mironov, Did you update the installation part of the library ? In your code some properties are not used anymore (senderID) this is why you should check the configuration.

Dallas62 avatar May 22 '20 16:05 Dallas62

@Dallas62 thanks for the prompt reply. Yeah, sure, SENDER_ID is there, just dropped that import not to clutter the snippet.

I also updated native part

#import <RNCPushNotificationIOS.h>

...

// Required to register for notifications
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
  [RNCPushNotificationIOS didRegisterUserNotificationSettings:notificationSettings];
}
// Required for the register event.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
  [RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
// Required for the notification event. You must call the completion handler after handling the remote notification.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
  [RNCPushNotificationIOS didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
// Required for the registrationError event.
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
  [RNCPushNotificationIOS didFailToRegisterForRemoteNotificationsWithError:error];
}
// Required for the localNotification event.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
  [RNCPushNotificationIOS didReceiveLocalNotification:notification];
}

As I mentioned, I was able to receive a plain notification when the app is killed, the only issue to make onNotification working when app is in the background/foreground.

alex-mironov avatar May 22 '20 16:05 alex-mironov

Ok, since you mentioned iOS code, is it a bug on iOS or Android ? If it's iOS, this is not an issue from this library

Dallas62 avatar May 22 '20 17:05 Dallas62

heh, yeah it's iOS...

alex-mironov avatar May 22 '20 20:05 alex-mironov

@alex-mironov we also having this issue - we are able to receive and show the push notification when app is in background. However, when app is in the foreground, push notification is not received and shown.

We have also added the following in AppDelegate.m


//Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
  completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
}

Please let us know if you find a solution to your issue

snamstorm avatar May 25 '20 08:05 snamstorm

Same in IOS onNotification is not working while app is in foreground and a message arrives. for time being we are using import messaging from '@react-native-firebase/messaging'; to detect the message arrival

messaging().onMessage(async (remoteMessage) => { console.log("onMessage", remoteMessage); if (!remoteMessage) return; if (CURRENT_OS === 'ios') return handleIosInteraction(remoteMessage); return handleAndroidInteraction(remoteMessage); }) but this does not address on notification tap issue while app is in foreground

Madhu-Yalavarthi avatar May 28 '20 04:05 Madhu-Yalavarthi

https://github.com/react-native-community/push-notification-ios/issues/107 ?

Dallas62 avatar May 29 '20 19:05 Dallas62

Also https://github.com/react-native-community/push-notification-ios/issues/63

Dallas62 avatar May 29 '20 19:05 Dallas62

@alex-mironov we also having this issue - we are able to receive and show the push notification when app is in background. However, when app is in the foreground, push notification is not received and shown.

We have also added the following in AppDelegate.m


//Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
  completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
}

Please let us know if you find a solution to your issue

@snamstorm I was also facing a similar issue. Not able to get this working in background for ios. Can you help me out to figure out what might be wrong?

peeyushagg avatar Jun 03 '20 17:06 peeyushagg

I think I am also facing a similar issue in iOS.
The notification arrives. If I click on the notification the app comes to the foreground but the onNotification handler is not called. In the XCode I see the log:

-[RNFirebaseNotifications sendJSEvent:name:body:] [Line 411] Multiple notification open events received before the JS Notifications module has been initialised

I call PushNotification.configure({ onNotification: handleNotificationClick }); from index.js so timing should not be the issue. @alex-mironov do you see the same log in XCode? If not I guess I should open a new ticket ;)

mathiasmoeller avatar Jun 04 '20 14:06 mathiasmoeller

@Dallas62 shouldn't onNotification in the NotificationHandler of this lib still fire?

I have things set up correctly I believe with push-notification-ios. When the app is in the background I receive the local scheduled notification just fine (so I assume my config with push-notification-ios is ok) but onNotification is never triggered.

jSkrills avatar Jun 04 '20 23:06 jSkrills

@Dallas62 you were right. On the push-notification-ios#107 issue you eluded to the fix pointed out here enabled me to begin receiving onNotification events while the app was in the background or foreground. Thanks for your pointers!

jSkrills avatar Jun 05 '20 00:06 jSkrills

Yes this fix also worked for me! Thanks for pointing it out again.

mathiasmoeller avatar Jun 05 '20 09:06 mathiasmoeller

@alex-mironov @snamstorm I am now facing the opposite problem. onNotification is called correctly when coming from foreground or background but it is not called when the app was killed. The app just launches normally. Could you maybe let me know how you did the configuration? I am calling PushNotification.configure from index.js so timing should not be the issue I guess. For Android it works correctly this way. I will also create a new issue for it since this is not really related. Just wanted your feedback since it seems to be working for you ;)

mathiasmoeller avatar Jul 03 '20 10:07 mathiasmoeller

    <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:configChanges="keyboard|keyboardHidden|orientation|screenSize"
    android:windowSoftInputMode="adjustResize" >
      <intent-filter>
      <action android:name="android.intent.action.MAIN" />
      <category android:name="android.intent.category.INFO" />
      </intent-filter>
    </activity>

Ajmal0197 avatar Sep 05 '20 13:09 Ajmal0197

I am also facing similar issue in IOS.

When app is in foreground / background, onNotification handler is not getting called when notification is received, though this is working perfectly fine in android.

nattri avatar Nov 30 '20 13:11 nattri

@nattri, Have you tried the adjustment I mentioned above?

jSkrills avatar Dec 06 '20 14:12 jSkrills

I am also facing similar issue in IOS.

When app is in foreground / background, onNotification handler is not getting called when notification is received, though this is working perfectly fine in android.

hi can you please help me on android notification to get the event in backgroud app.

vipin-ios avatar Apr 13 '21 18:04 vipin-ios

@alex-mironov @snamstorm I am now facing the opposite problem. onNotification is called correctly when coming from foreground or background but it is not called when the app was killed. The app just launches normally. Could you maybe let me know how you did the configuration? I am calling PushNotification.configure from index.js so timing should not be the issue I guess. For Android it works correctly this way. I will also create a new issue for it since this is not really related. Just wanted your feedback since it seems to be working for you ;)

How did you solve this?

Pra3t0r5 avatar May 28 '21 00:05 Pra3t0r5

@alex-mironov @snamstorm I am now facing the opposite problem. onNotification is called correctly when coming from foreground or background but it is not called when the app was killed. The app just launches normally. Could you maybe let me know how you did the configuration? I am calling PushNotification.configure from index.js so timing should not be the issue I guess. For Android it works correctly this way. I will also create a new issue for it since this is not really related. Just wanted your feedback since it seems to be working for you ;)

How did you solve this?

Haven't solved it yet

nattri avatar May 31 '21 07:05 nattri

@alex-mironov @snamstorm I am now facing the opposite problem. onNotification is called correctly when coming from foreground or background but it is not called when the app was killed. The app just launches normally. Could you maybe let me know how you did the configuration? I am calling PushNotification.configure from index.js so timing should not be the issue I guess. For Android it works correctly this way. I will also create a new issue for it since this is not really related. Just wanted your feedback since it seems to be working for you ;)

How did you solve this?

Haven't solved it yet

This solved it for me:

  • SplashActivity
package com.trique.app; // Change this to your package name.

import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;

public class SplashActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtras(getIntent().getExtras());  // <--- ADD THIS
        startActivity(intent);
        finish();
    }
}
  • MainActivity
package com.trique.app;

import com.facebook.react.ReactActivity;
import org.devio.rn.splashscreen.SplashScreen;
import android.os.Bundle;
import android.content.Intent;

public class MainActivity extends ReactActivity {

  /**
   * Returns the name of the main component registered from JavaScript. This is used to schedule
   * rendering of the component.
   */
  @Override
  protected String getMainComponentName() {
    return "com.trique.app";
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
      SplashScreen.show(this);
      super.onCreate(savedInstanceState);
  }
}
  • AndroidManifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.trique.app"
  xmlns:tools="http://schemas.android.com/tools">
  <uses-permission android:name="android.permission.INTERNET"/>
  <uses-permission android:name="android.permission.CAMERA"/>
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
  <uses-permission android:name="android.permission.RECORD_AUDIO"/>
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  <uses-permission android:name="android.permission.VIBRATE"/>
  <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
  <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">
    <meta-data android:name="com.dieam.reactnativepushnotification.notification_foreground" android:value="false"/>
    <meta-data android:name="com.dieam.reactnativepushnotification.notification_color" android:resource="@color/white"/>
    <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>

    <activity android:name=".SplashActivity" android:theme="@style/SplashTheme" android:launchMode="singleTask" 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:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode" android:windowSoftInputMode="adjustResize" android:launchMode="singleTask" android:exported="true">
      <intent-filter>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        <data android:host="share.triqueapp.com" android:scheme="https"/>
      </intent-filter>
    </activity>

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

  </application>
</manifest>

Pra3t0r5 avatar May 31 '21 23:05 Pra3t0r5

Facing the same issue in IOS ,onNotification is not triggered but it is triggering if the user clicks on the recieved notification.need Onnotification to trigger as soon as we get the remote notification

singulurisuma avatar Nov 17 '21 03:11 singulurisuma

I'm to update the UI when onNotification arrives. In general onNotification works as expected when app is killed. It wakes up -> onNotification gets called.

BUT onNotification doesn't seem to be getting called when the app is NOT killed, i.e. in foreground or background.

I saw people reporting similar issues for local notifs, but I assume for remote notifications it's different?

Can someone suggest what could be wrong?

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

const Root = () => {
  PushNotification.configure({
    onRegister: pushToken => {
      console.log(pushToken.token)
    },

    onNotification: notification => {
      console.log('Notification received', notification)
      notification.finish(PushNotificationIOS.FetchResult.NoData)
    },
    onError: err => {
      console.log('Error configuring notifications', err)
    },

    senderID: SENDER_ID,

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

    popInitialNotification: true,
    requestPermissions: Platform.OS === 'android',
  })

  return <Router />
}

The library version:

    "react-native-push-notification": "^3.5.0",

abhaya-kumar-sahoo avatar Dec 24 '22 18:12 abhaya-kumar-sahoo