Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

onNotification is not calling when app is in background #1431

Closed
rizwanshaikh199091 opened this issue May 11, 2020 · 68 comments
Closed

onNotification is not calling when app is in background #1431

rizwanshaikh199091 opened this issue May 11, 2020 · 68 comments

Comments

@rizwanshaikh199091
Copy link

Bug

When I am calling fcm server push notification api data is not showing on onNotification function.

Environment info

react-native info output:

 // paste it here

Library version: 3.4.0

Steps To Reproduce

I use the following code for recieving push notification

  1. Call the service from postman collection for fcm
  2. we got data in onNotification when app is in foreground but not in backgorund
    ...

Describe what you expected to happen:

Reproducible sample code

PushNotification.configure({
// (optional) Called when Token is generated (iOS and Android)
onRegister: function (token) {
console.log("TOKEN:", token);
thats.setState({deviceToken:token});
},

  // (required) Called when a remote or local notification is opened or received
  onNotification: function (notification) {
    

    console.log('** NOTIFICATION: **', notification);

  if (Platform.OS === 'ios') {
    if (notification.alert.length !== 0) {
      //handleNotification(notification)
      notification.finish(PushNotificationIOS.FetchResult.NoData);
    }
  } else {
    //handleNotification(notification)
  }

  
  },

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

 
  requestPermissions: true,
});

PushNotification.popInitialNotification((notification) => { 
  console.log(notification); 
})
@Dallas62
Copy link
Collaborator

Hi @rizwanshaikh199091
Can you provide more information ?
Where did you put PushNotification.configure ? Inside a component ?
Can you reproduce it in example project ?

@rizwanshaikh199091
Copy link
Author

rizwanshaikh199091 commented May 11, 2020

Hi @Dallas62

Thanks for quick reply, I put my code inside constructor function.

This is the code that I put inside constructor function of my call and calling api from postman.

    PushNotification.configure({
      // (optional) Called when Token is generated (iOS and Android)
      onRegister: function (token) {
        console.log("TOKEN:", token);
        thats.setState({deviceToken:token});
      },
    
      // (required) Called when a remote or local notification is opened or received
      onNotification: function (notification) {
        

        console.log('** NOTIFICATION: **', notification);

      if (Platform.OS === 'ios') {
        if (notification.alert.length !== 0) {
          //handleNotification(notification)
          notification.finish(PushNotificationIOS.FetchResult.NoData);
        }
      } else {
        //handleNotification(notification)
      }

      
      },
    
      // 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,
    
     
      requestPermissions: true,
    });

    PushNotification.popInitialNotification((notification) => { 
      console.log(notification); 
    })

I have attached a few screenshots taken in both the conditions. Please have a look.
Screenshot 2020-05-11 at 4 39 11 PM

Screenshot 2020-05-11 at 4 39 49 PM

Screenshot 2020-05-11 at 4 42 22 PM

Please advice. Thanks

@Dallas62
Copy link
Collaborator

Dallas62 commented May 11, 2020

Hi @Dallas62

Thanks for quick reply, I put my code inside constructor function.

This is the code that I put inside constructor function of my call and calling api from postman.

I have attached a few screenshots taken in both the conditions. Please have a look.

Please advice. Thanks

I think you should put the PushNotification.configure Outside of a component,
Take a look at example

@rizwanshaikh199091
Copy link
Author

Okay let me try this

@davidsalib
Copy link

davidsalib commented May 11, 2020

I'm having the same issue. Tried it both in componentDidMount and outside of a component. Same issue.

@Dallas62
Copy link
Collaborator

Okay let me try this

I didn't notice, but in your screenshot there is the data, which means you received the notification, so everything is OK, no ?

https://firebase.google.com/docs/cloud-messaging/android/receive#handling_messages

onMessageReceived is provided for most message types, with the following exceptions:

Notification messages delivered when your app is in the background: In this case, the notification is delivered to the device’s system tray. A user tap on a notification opens the app launcher by default.

Messages with both notification and data payload, when received in the background: In this case, the notification is delivered to the device’s system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.

App state Notification Data Both
Foreground onMessageReceived onMessageReceived onMessageReceived
Background System tray onMessageReceived Notification: system trayData: in extras of the intent.

I know this is not what you expect, but I don't think we can change this.

@taymer
Copy link
Contributor

taymer commented May 19, 2020

Same issue here, I tried with the example app and onNotification is always called except when app is in backgroud.
The App is just cloned from git example.
I'm trying it in an Android 7.0 device

@taymer
Copy link
Contributor

taymer commented May 19, 2020

Ok, i figured it out: the problem is that onNewIntent() is not called on ReactContextBaseJavaModule
This solution worked in the example app: https://stackoverflow.com/a/45749359/829300

I modified
public class RNPushNotification implementing Application.ActivityLifecycleCallbacks and overriding

public void onActivityStarted(Activity activity) {
    Intent intent = activity.getIntent();
    Bundle bundle = this.getBundleFromIntent(intent);
    if (bundle != null) {
        bundle.putBoolean("foreground", false);
        intent.putExtra("notification", bundle);
        mJsDelivery.notifyNotification(bundle);
    }
}

taymer added a commit to taymer/react-native-push-notification that referenced this issue May 20, 2020
@taymer taymer mentioned this issue May 20, 2020
Dallas62 added a commit that referenced this issue May 20, 2020
@wbercx
Copy link

wbercx commented May 24, 2020

public void onActivityStarted(Activity activity) {
    Intent intent = activity.getIntent();
    Bundle bundle = this.getBundleFromIntent(intent);
    if (bundle != null) {
        bundle.putBoolean("foreground", false);
        intent.putExtra("notification", bundle);
        mJsDelivery.notifyNotification(bundle);
    }
}

@taymer This appears to be a source of crashes now. I've received the following stacktrace a number of times over the weekend (Release build).

I assume this means mJsDelivery may not always be initialised when onActivityStarted runs.

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.dieam.reactnativepushnotification.modules.d.c(android.os.Bundle)' on a null object reference
  at com.dieam.reactnativepushnotification.modules.RNPushNotification.onActivityStarted(RNPushNotification.java:5)
  at android.app.Application.dispatchActivityStarted(Application.java:406)
  at android.app.Activity.dispatchActivityStarted(Activity.java:1239)
  at android.app.Activity.onStart(Activity.java:1724)
  at androidx.fragment.app.d.onStart(FragmentActivity.java:1)
  at androidx.appcompat.app.e.onStart(AppCompatActivity.java:1)
  at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1432)
  at android.app.Activity.performStart(Activity.java:7848)
  at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3294)
  at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
  at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
  at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
  at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
  at android.os.Handler.dispatchMessage(Handler.java:107)
  at android.os.Looper.loop(Looper.java:214)
  at android.app.ActivityThread.main(ActivityThread.java:7356)
  at java.lang.reflect.Method.invoke(Method.java:-2)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

@Dallas62
Copy link
Collaborator

Hi @wbercx
Can you provide the android:launchMode of your activity ?

@wbercx
Copy link

wbercx commented May 25, 2020

@Dallas62 singleTop.

I do not remember the exact reason why though. I feel like I've had to mess with that a few times over the years. I wrote a particularly useless commit message for that too...

EDIT:
I ended up making the following change. Not an Android developer, so I don't know if it makes a real difference, but at least it is not broken. Then again, the original worked for me as well.

    public RNPushNotification(ReactApplicationContext reactContext) {
        super(reactContext);

        reactContext.addActivityEventListener(this);

+        // This is used to delivery callbacks to JS. Instantiated before registering activityLifeCycleCallbacks.
+        mJsDelivery = new RNPushNotificationJsDelivery(reactContext);

        Application applicationContext = (Application) reactContext.getApplicationContext();
        applicationContext.registerActivityLifecycleCallbacks(this);

        // The @ReactNative methods use this
        mRNPushNotificationHelper = new RNPushNotificationHelper(applicationContext);
-        // This is used to delivery callbacks to JS
-        mJsDelivery = new RNPushNotificationJsDelivery(reactContext);

        mRNPushNotificationHelper.checkOrCreateDefaultChannel();
    }

@Dallas62
Copy link
Collaborator

@wbercx
Ok, I reverted the PR and changed the code in the JS side, this might be good.
I do more tests and release a fix ASAP

@wbercx
Copy link

wbercx commented May 25, 2020

@Dallas62 Have a look at the above, I edited it just moments earlier.

@Dallas62
Copy link
Collaborator

@wbercx This is not a good solution anyway, this cause a bug on background by triggering the notification again and again when you switch from background / foreground state. #1455
The check in the JS side is not enough to handle properly the popInitialNotitication it's just a boolean, once it's true nothing can be done.
I switched to the id of the notification but I need to check iOS.

@AndersonSchmidt
Copy link

Is this fixed? It's not working for me either.

@Dallas62
Copy link
Collaborator

Dallas62 commented Jun 9, 2020

Hi @AndersonSchmidt
The main reason this is not triggered on Android is that you put .configure inside a component.
Move it outside of a component and this should work.

@AndersonSchmidt
Copy link

AndersonSchmidt commented Jun 9, 2020

@Dallas62 First of all, thank you for your response. I already tried to do it as the image shows. It only calls onNotification if the app is in Foreground. If I exit or navigate to another app, I receive the notification but onNotification is not called. I'm using version 3.5.1. I don't know what to do anymore, I spent all day trying to fix this. I would be really glad if you have any solution for me. Thanks.
hd9NyNM

@Dallas62
Copy link
Collaborator

Dallas62 commented Jun 9, 2020

In another issue:
Can you provide AndroidManifest ?
Also try to clean Android build cache and upgrade to 3.5.2.

@AndersonSchmidt
Copy link

@Dallas62
image

@taymer
Copy link
Contributor

taymer commented Jun 9, 2020

@Dallas62 what version of android is your device ? I've still the same issue with 7.0

@AndersonSchmidt
Copy link

AndersonSchmidt commented Jun 9, 2020

@taymer But didn't you manage to solve it? Your solution was even merged, but I saw that it was removed on version 3.5.2. By the way, I tested on android 8 and 10 and it's not working.

@taymer
Copy link
Contributor

taymer commented Jun 9, 2020

@AndersonSchmidt I've tried 3.5.2, but I'm still using my piece of code, which works with the app in background, but not if it's closed (it calls onNotification only if you put the app in background and then again in foreground) . Sadly for now I've not enough time to check this issue.

@AndersonSchmidt
Copy link

@taymer I understand. Do you have any tips/suggestions for me? I need to call onNotification ALWAYS when a notification is received to update a redux state to add a notification badge number on my hamburger button, so the user will know if and how many notifications he has. I was progressing well but got stuck on this. Check the badge I'm using.

@taymer
Copy link
Contributor

taymer commented Jun 10, 2020

@AndersonSchmidt I've just tried the example app with version 3.5.2 and it works like a charm, so the problem is in our use of the library

@Dallas62
Copy link
Collaborator

I will retest this at the end of the day.
The main reason of this problem is when you try to manage the callback of onNotification inside a component.

@Dallas62
Copy link
Collaborator

Also check the launchMode of your AndroidManifest @AndersonSchmidt in example project the value is singleTop.

@taymer
Copy link
Contributor

taymer commented Jun 10, 2020

@Dallas62 In the example inside the library the launch mode is singleTask

@kirantripathi
Copy link

kirantripathi commented Aug 26, 2020

Screen Shot 2020-08-26 at 11 34 12

@Dallas62 thanks for that, now I am getting notification response in onNotification callback, but when I click notification "userInteraction" key is not present in quit state , and I am not able to perform any operation on it. I need to perform some operation when click on notification.so for that what should I do . can you help me on that?

@naveenprakash74
Copy link

This is why onNotification is not trigger.
Look at my previous message.

You can’t use notification field with background handler.
You must use data (and not combined with notification).
Then if you want to notify the user, trigger a local notification.

I am still facing this problem. can you give some example code? Thank you

@romelbonnie
Copy link

This is why onNotification is not trigger.
Look at my previous message.

You can’t use notification field with background handler.
You must use data (and not combined with notification).
Then if you want to notify the user, trigger a local notification.

I've followed this process. I sent data-only and trigger a local notification. But when I press the notification it will trigger another local notification. Can you please give an example on how you implement receiving remote notifications and trigger local notification.

@Dallas62
Copy link
Collaborator

Hi @romelbonnie
There is an userInteraction field in the notification object.
true == user has pressed the notification.
Regards,

@romelbonnie
Copy link

Oh I see. Thank you @Dallas62

@ehsanmolaei991
Copy link

2020-11-29 15_54_54-App js - Mutalee - Visual Studio Code
2020-11-29 15_55_17-App js - Mutalee - Visual Studio Code

@Dallas62
Please give me a solution
i configure PushNotification out of component (Bottom of App Class)
and call localNotification but nothing happened

but i see "console.log('TOKEN:', token);" in debugger and just it

please help me !!!

@Dallas62
Copy link
Collaborator

Hi,

There is no channelId defined.

@ehsanmolaei991
Copy link

Tnx Man.

Hi,

There is no channelId defined.

Tnx Man

@ehsanmolaei991
Copy link

2020-11-30 13_30_46-AndroidManifest xml - Mutalee - Visual Studio Code
2020-11-30 13_32_10-AndroidManifest xml - Mutalee - Visual Studio Code
2020-11-30 13_32_25-AndroidManifest xml - Mutalee - Visual Studio Code
2020-11-30 13_32_37-AndroidManifest xml - Mutalee - Visual Studio Code
2020-11-30 13_33_08-NotificationManeger js - Mutalee - Visual Studio Code
2020-11-30 13_35_12-NotificationManeger js - Mutalee - Visual Studio Code

@Dallas62
Hi again
I can't solve my problem
I can use local notification for myapp but i can't use remote mode
I add google service and firebase and google.json in build.gradle and android/app

I use this AndroidManifest
and put this sender Id

please help me,

@Dallas62
Copy link
Collaborator

Hi @rizwanshaikh199091
You are using deprecated properties in your AndroidManifest, please refer to the changelog for upgrade your manifest.
Also you don't provide the Payload of the notification, it's not possible to help you without it.

Refer to:
https://firebase.google.com/docs/cloud-messaging/concept-options
and
https://github.com/zo0r/react-native-push-notification/blob/master/trouble-shooting.md#1-local-notifications
For more informations.

Regards,

minhnc added a commit to minhnc/react-native-push-notification that referenced this issue Mar 24, 2021
* commit '1d497e60a142b4a846907ec19b80ab72a5ae5c8d': (109 commits)
  Bump to 3.5.2.
  Remove extra interface.
  Fix sounds volume and DND is ignored. Fix zo0r#1455 `onNotification fires every time when the app goes from background to foreground`
  Update README.md
  Bump to 3.5.1.
  Switch from support library to androidx. zo0r#1449
  Bump to 3.5.0.
  Move back onNewToken to Firebase service.
  zo0r#1431
  feat: explicitly override onNewToken
  Change from 18 months to 1 year
  feat: multiple push providers
  Missing change on variable name.
  Prevent sound to be mute in default state.
  Update CHANGELOG.md.
  Prevent crash for NaN.
  Bump to version 3.4.0.
  Put deleteInstanceId() in a separate thread.
  Use directly the callNative for `abandonPermissions`.
  Changes in example Application.
  ...

# Conflicts:
#	android/src/main/java/com/dieam/reactnativepushnotification/modules/RNPushNotificationListenerService.java
@SanatChoubey
Copy link

Hey I found this issue in Ios side

@stephanoparaskeva
Copy link

stephanoparaskeva commented Mar 30, 2021

@Dallas62

I am sending a data notification and the onNotification function is not called when the app is in the background. But it is called when the application is in the foreground.

{
 "to" : "fXJ_A95kTQOqm6koxOFBwh:APA91bEAUKYfn4dUhxa00yKNzs4F0b3nAh8oxXGC3cegOxhI2kCQN0XbZ0elI9M640W4SYllNF_rHQOWm8V1ryaueUN6h9ddfX2n9xfQplAzzRzBxVqDdyLa0Yl7NjigsZtlDqTeVS1i",
 "data" : {
     "initiatorId" : "127167807"
 },
  "priority": "high"
}

@SanatChoubey
Copy link

I am sending a data notification and the onNotification function is not called when the app is in the background. But it is called when the application is in the foreground.

{
 "to" : "fXJ_A95kTQOqm6koxOFBwh:APA91bEAUKYfn4dUhxa00yKNzs4F0b3nAh8oxXGC3cegOxhI2kCQN0XbZ0elI9M640W4SYllNF_rHQOWm8V1ryaueUN6h9ddfX2n9xfQplAzzRzBxVqDdyLa0Yl7NjigsZtlDqTeVS1i",
 "data" : {
     "initiatorId" : "127167807"
 },
  "priority": "high"
}

hey @stephanoparaskeva
I got know after a day is that javascript code never run in background you need to be in app so it basically work when you tap notifications or in foreground .
but this case not applied on android android works in background with headless js.
Thanks

@Dallas62
Copy link
Collaborator

Hi @stephanoparaskeva
For iOS, please refer to the iOS repository.
For Android make sure Android Manifest is configured as described in the Readme.

In general, do not put .configure() inside a component.
Regards

@stephanoparaskeva
Copy link

@Dallas62
This is my index.js file:

const onRegister = ({ token }: TDeviceInfo) => AsyncStorage.setItem(FCM_OR_APNS_TOKEN, token);

PushNotification.configure({
  onRegister,
  onNotification,
  popInitialNotification: true,
  requestPermissions: true,
});

const findTokenEvent = (evt: TEvent) =>
  evt.name === VoipPushNotification.RNVoipPushRemoteNotificationsRegisteredEvent;

VoipPushNotification.addEventListener('didLoadWithEvents', (events: Array<TEvent>) => {
  const apnsVoipToken = events.find(findTokenEvent)?.data;
  AsyncStorage.setItem(APNS_VOIP_TOKEN, apnsVoipToken || '');
});


AppRegistry.registerComponent(name, () => app);

This is my androidmanifest.xml file:
https://pastebin.com/d9Ut5ZYV

I think it should be correct?

@Dallas62
Copy link
Collaborator

@stephanoparaskeva
Make sure you are on the latest version and the channel "QB_PUSH_NOTIFICATION_CHANNEL" is created.
You can remove all the "C2D" things inside you AndroidManifest.

Since there is also, another library which can intercept you code, you can check logs with: adb logcat.

Regards,

@stephanoparaskeva
Copy link

stephanoparaskeva commented Mar 30, 2021

@stephanoparaskeva
Make sure you are on the latest version and the channel "QB_PUSH_NOTIFICATION_CHANNEL" is created.
You can remove all the "C2D" things inside you AndroidManifest.

Since there is also, another library which can intercept you code, you can check logs with: adb logcat.

Regards,

I commented out the QB_PUSH_NOTIFICATION_CHANNEL so it should work as default right?
I removed all C2D things
I upgraded to latest "react-native-push-notification": "^7.2.3"
Still onNotification does not run in the background.

Here is my updated androidManifest.xml
https://pastebin.com/Vh8G45dr

What should I look for in logcat?
What else could be causing this issue that you have noticed?

@stephanoparaskeva
Copy link

stephanoparaskeva commented Mar 30, 2021

@Dallas62 It works for me on IOS but not on android in the background. This is the request I make on IOS and it works:

lola \
-bundleId com.euclid \
-device 35214b2782c4445231d7512dfa2bfed89b9fcde32d284e1acd5633d631c4ef2f \
-teamId HLR7ND6WN5 \
-authKey AuthKey_SHVZ2CXB5P.p8 \
-notificationType background \
-json "{ \"aps\": { \"content-available\": 1 }, \"initiatorId\": 127167807  }"

But this does not, for android and this only works in the foreground for android:

{
 "to" : "fXJ_A95kTQOqm6koxOFBwh:APA91bEAUKYfn4dUhxa00yKNzs4F0b3nAh8oxXGC3cegOxhI2kCQN0XbZ0elI9M640W4SYllNF_rHQOWm8V1ryaueUN6h9ddfX2n9xfQplAzzRzBxVqDdyLa0Yl7NjigsZtlDqTeVS1i",
 "data" : {
     "initiatorId" : "127167807"
 },
  "priority": "high"
}

@Dallas62
Copy link
Collaborator

Hi @stephanoparaskeva
Did you create the channel? By calling .createChannel(...) ?

@stephanoparaskeva
Copy link

stephanoparaskeva commented Mar 31, 2021

Hi @Dallas62
I have created the channel, but this did not help, here is the manifest:

        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_foreground"
            android:value="false"/>
        <service
            android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationRegistrationService" />
        <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>
        <meta-data
            android:name="com.dieam.reactnativepushnotification.notification_channel_name"
            android:value="QB_PUSH_NOTIFICATION_CHANNEL" />
        <meta-data
            android:name="com.dieam.reactnativepushnotification.notification_channel_description"
            android:value="Channel for Quickblox push notification events" />
        <meta-data
            android:name="com.dieam.reactnativepushnotification.notification_color"
            android:resource="@color/primary" />

        <service android:name="com.quickblox.messages.services.fcm.QBFcmPushInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

And here is the channel creation in index.js

  PushNotification.configure({
    onRegister,
    onNotification,
    popInitialNotification: true,
    requestPermissions: true,
  });

  PushNotification.createChannel(
    {
      channelId: 'QB_PUSH_NOTIFICATION_CHANNEL', // (required)
      channelName: 'QB_PUSH_NOTIFICATION_CHANNEL', // (required)
      playSound: false, // (optional) default: true
      soundName: 'default', // (optional) See `soundName` parameter of `localNotification` function
    },
    created => console.log(`createChannel returned '${created}'`) // (optional) callback returns whether the channel was created, false means it already existed.
  );

I am sending the notification via Postman and it triggers onNotification when the app is in the foreground, but it does not trigger onNotification when the app is in the background.

I am sending a data message via postman and here is the JSON:

{
 "to" : "fXJ_A95kTQOqm6koxOFBwh:APA91bEAUKYfn4dUhxa00yKNzs4F0b3nAh8oxXGC3cegOxhI2kCQN0XbZ0elI9M640W4SYllNF_rHQOWm8V1ryaueUN6h9ddfX2n9xfQplAzzRzBxVqDdyLa0Yl7NjigsZtlDqTeVS1i",
 "data" : {
     "initiatorId" : "127167807"
 },
  "priority": "high"
}

This works in the foreground but not in the background

Regards

@Dallas62
Copy link
Collaborator

@stephanoparaskeva
You can try to add the channel as default channel:

  <meta-data
      android:name="com.dieam.reactnativepushnotification.default_notification_channel_id"
      android:value="QB_PUSH_NOTIFICATION_CHANNEL" />

If the channel is not created and used, the notification will not work.

@stephanoparaskeva
Copy link

stephanoparaskeva commented Mar 31, 2021

Hi @Dallas62

  <meta-data
      android:name="com.dieam.reactnativepushnotification.default_notification_channel_id"
      android:value="QB_PUSH_NOTIFICATION_CHANNEL" />

I have tried this too and it doesnt work. I have also removed this channel entirely and it doesnt work.
Nothing about the message specifies a channel:

{
 "to" : "fXJ_A95kTQOqm6koxOFBwh:APA91bEAUKYfn4dUhxa00yKNzs4F0b3nAh8oxXGC3cegOxhI2kCQN0XbZ0elI9M640W4SYllNF_rHQOWm8V1ryaueUN6h9ddfX2n9xfQplAzzRzBxVqDdyLa0Yl7NjigsZtlDqTeVS1i",
 "data" : {
     "initiatorId" : "127167807"
 },
  "priority": "high"
}

It works in the foreground but does not work in the background. There must some other reason, the request is made via postman and is a data request, it does not specify a notification field and it has data The android manifest follows the readme, the package is on the latest version and the configure() function is run outside of any component.

The data notification is sent via postman but the application never runs the onNotification function when the app is closed. It is run successfully when the application is in the foreground.

On IOS I can successfully get the onNotification function to run when the app is closed when sending a data/background APNS push.

What have I done wrong on the android side?

Here are some screenshots of the postman request:
Screenshot 2021-03-31 at 10 22 38
Screenshot 2021-03-31 at 10 22 49

And here is a screenshot of the console.warn(notification) in onNotification function when in the foreground.
Screenshot 2021-03-31 at 10 25 34

@Dallas62
Copy link
Collaborator

You must setup and use a channel (created, set as default of specified in notification payload).
If not, background notifications won't work.

https://developer.android.com/training/notify-user/channels

Caution: If you target Android 8.0 (API level 26) and post a notification without specifying a notification channel, the notification does not appear and the system logs an error.

Firebase documentation (Android 2b.):
https://firebase.google.com/docs/cloud-messaging/http-server-ref#notification-payload-support

android_channel_id

Then, we will be able to investigate.

If everything is set up, you can check the log of the device with logcat.
Open a new issue with the log of logcat when you send a the notification (app in background).

@stephanoparaskeva
Copy link

Hi @Dallas62
Here is the new issue created with the LOGCAT logs and the channel_id:
#1930

@Harish-Sankey
Copy link

Hi @Dallas62
Is it compulsory to change android:launchMode="standard" to ( singleTop or singleTask ) for this library, since for me onNotification() is not getting called when app is in background (when lauchMode is standard) ?

I am using "react-native-push-notification": "^7.4.0"

@Arunprabhuk
Copy link

how can i create push notification without using firebase and onesignal?
thanks

@naveenprakash74
Copy link

without firebase you can not create remote push notification

if you want to create local push notifications then you can create it with react native push notification module

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

No branches or pull requests