phonegap-plugin-push on("notification") event is not firing when app is in background
Asked Answered
S

3

5

I am using following plugin for push notification in Ionic2

http://ionicframework.com/docs/native/push/

Expected Behaviour: When app is closed, And notification received, And when user tap the notification, on("notification") event should fire after app opens.

Actual Behaviour: I am getting notification successfully. But When Application is in background or closed, at that time when I receive notification and I tap the notification, on("notification") event is not firing.

Cordova version 7.0.1 Android version 6.2.3

My code:

this.platform.ready().then(() => {
    this.pushsetup();
});

private pushOptions: PushOptions;
private pushObject: PushObject;
pushsetup() {
    // to check if we have permission
    this.push.hasPermission()
        .then((res: any) => {
            if (res.isEnabled) {
                console.log('We have permission to send push notifications');
                // configuration of push notification
                this.pushOptions = {
                    android: {
                        senderID: 'XXXXXXXXXXX',
                        icon: 'icon_notification'
                    },
                    ios: {
                        alert: 'true',
                        badge: true,
                        sound: 'false',
                        senderID: 'XXXXXXXXXXX'
                    },
                    windows: {}
                };
                this.pushObject = this.push.init(this.pushOptions);

                // attach push events
                this.storage.get('isPushRegistered')
                    .then(isPushRegistered => {
                        if( !isPushRegistered ){
                            this.pushObject.on('registration').subscribe((registration: any) => {
                                console.log('Device registered', registration)
                                this.storage.set('isPushRegistered', true)
                            });
                        }
                    })


                this.pushObject.on('notification').subscribe((notification: any) => {
                    console.log('Received a notification', notification)
                });
                this.pushObject.on('error').subscribe(error => console.error('Error with Push plugin', error));
            }
        });
}

So, on my code, you can see this.pushObject.on('notification') event. that is not firing when app is closed.

Thank you for your time and support.

Sandie answered 12/9, 2017 at 12:25 Comment(3)
Have you set "content-available": 1 in your payload data which is sent from backend.Levina
Yes I have set it. But still no success. Plus I have read phonegap plugin documentation that stats as follow: "If the user has killed the application then no further processing of the push data will occur." github.com/phonegap/phonegap-plugin-push/blob/master/docs/…Sandie
When app is closed, then you cannot execute any functions of phone-gap-push. But when it is in background you can execute by setting "content-available": 1.Levina
G
10

This is not the issue with client side code. This issue is occuring because of the notification payload.

From Official docs of phonegap-plugin-push

Notifications behave differently depending on the foreground/background state of the receiving app and the payload you send to the app.

For instance if you send the following payload: phonegap-plugin-push/

{
  "notification": {
    "title": "Test Notification",
    "body": "This offer expires at 11:30 or whatever",
    "notId": 10
  }
}

When your app is in the foreground, any on('notification') handlers you have registered will be called. However, if your app is in the background, the notification will show up in the system tray. Clicking on the notification in the system tray will start the app but your on('notification') handler will not be called as messages that have notification payloads will not cause the plugins onMessageReceived method to be called.

If you send a payload with a mix of notification & data objects like this:

{
    "notification": {
        "title": "Test Notification",
        "body": "This offer expires at 11:30 or whatever",
        "notId": 10
    },
    "data" : {
        "surveyID": "ewtawgreg-gragrag-rgarhthgbad"
    }
}

When your app is in the foreground any on('notification') handlers you have registered will be called. If your app is in the background, the notification will show up in the system tray. Clicking on the notification in the system tray will start the app and your on('notification') handler will not be called as messages that have notification payloads will not cause the plugins onMessageReceived method to be called.

My recommended format for your push payload when using this plugin (while it differs from Google's docs) works 100% of the time:

{
    "data" : {
        "title": "Test Notification",
        "body": "This offer expires at 11:30 or whatever",
        "notId": 10,
        "surveyID": "ewtawgreg-gragrag-rgarhthgbad"
    }
}

When your app is in the foreground any on('notification') handlers you have registered will be called. If your app is in the background, then the notification will show up in the system tray. Clicking on the notification in the system tray will start the app, and your on('notification') handler will be called with the following data:

{
    "message": "This offer expires at 11:30 or whatever",
    "title": "Test Notification",
    "additionalData": {
        "surveyID": "ewtawgreg-gragrag-rgarhthgbad"
    }
}

Link to the docs

Grecoroman answered 12/12, 2017 at 9:0 Comment(8)
Perfect! I spent a day to fix this and finally, this solved my problem.Crassus
workes perfect for android, but changing it break the notification for iosJakie
what if the app is totally closed ? say for instance my notification payload contains both, notification and data object. I asked same question here github.com/phonegap/phonegap-plugin-push/issues/2575Embody
hey @HiteshUpadhyay have u find any solution i am stuck here alsoEmbody
@KishanOza, Hi brother, the answer that I verified is the one that works for me. Note that, the data structure is very important here.Sandie
Yaah i tried at my end ..app is restart forcefully but still no luck on .on('notification') method.. can u send me your server side code..i mean the script ? @HiteshUpadhyayEmbody
what if I want to trigger (both on background and foreground) on('notification') as soon as the notification arrives, no whether if the user taps or swipes away the notification?Aundrea
What it boils down to is you cannot use FCM to send to both Android and iOS if you want your push notifications to work properly.Sleeve
L
0

Below is the code has worked for me. When the app is closed, and you receive a notification. If you want to handle the click event by looking into some payload data. Then have a look at below code:

pushObject.on('notification').subscribe((notification: any) => {

    // this method will be called when you click on notification when app is closed
    pushObject.finish()
       .then(e => {})
       .catch(e => { console.log("ERROR NOTIFICATION",e); })

}).catch(e => {
    console.log("ERROR NOTIFICATION",e);
})
Levina answered 13/9, 2017 at 13:23 Comment(2)
Thanks for your concern, can you share your code on github? both server and app code. The suggestion you gave me i tried but still not working.Sandie
I have created a gist have a look at it. gist.github.com/coolvasanth/ba61710cb68af4097acfe603765c2df3 feel free to ask if you have any doubts.Levina
B
0

You can check the forground by the following code:

pushObject.on('notification').subscribe((data: any) => {
      console.log('message -> ' + data.message);
      //if user using app and push notification comes
      if (data.additionalData.foreground) {
        // if application open, show popup
      }
      else{
       //if user NOT using app and push notification comes
      }

For more details to send push notifications in Ionic you can visit:

https://medium.com/@ankushaggarwal/push-notifications-in-ionic-2-658461108c59

Blatant answered 23/10, 2017 at 5:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.