[Android] How to receive notification data after tapping the notifcation while the app is in background?


#1

Hi,

Considering my app is running background or is off, when I receive a notification and tap on it, my app opens but I don’t receive any data from that notification.

Here is the piece of code I’m using :

initPushNotification() {
        if (!this.platform.is('cordova')) {
            console.warn('Push notifications not initialized. Cordova is not available - Run in physical device');
            return;
        }
        const options: PushOptions = {
            android: {
                senderID: MY_SENDER_ID
            },
            ios: {
                alert: 'true',
                badge: false,
                sound: 'true'
            },
            windows: {}
        };
        const pushObject: PushObject = this.push.init(options);

        pushObject.on('registration').subscribe((data: any) => {             
            // send notification token to server
            // ...
        });

        pushObject.on('notification').subscribe((data: any) => {
            console.log(data);
            this.notificationService.display(data);
        });

        pushObject.on('error').subscribe(error => console.error('Error with Push plugin' + error));
    }

I’m expecting to get log from that part but I don’t get anything :

pushObject.on('notification').subscribe((data: any) => {
            console.log(data);
            this.notificationService.display(data);
        });

NB : I only encounter the problem with Android, it’s working fine with iOS.

I’m using

@angular/*”: “5.0.0”,
"@ionic-native/push": “4.5.2”,
“cordova-plugin-device”: “1.1.7”,
“cordova-plugin-fcm”: “2.1.2”,

I’ve spent hours browsing Ionic docs, Stackoverflow and trying different stuff like this one but I don’t have ideas anymore. Any help would be appreciated.


#2

I found my mistake by reading this post from Github.

Instead of sending

{
  "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
  "notification" : {
    "body" : "great match!",
    "title" : "Portugal vs. Denmark",
    "icon" : "myicon"
    },
  "data": {
    "body" : "great match!",
    "title" : "Portugal vs. Denmark",
    "icon" : "myicon"
  }
}

I have to send

{
  "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
  "data": {
    "body" : "great match!",
    "title" : "Portugal vs. Denmark",
    "icon" : "myicon"
  }
}

and I now retrieve my data.