phonegap / phonegap-plugin-push

Register and receive push notifications
MIT License
1.94k stars 1.91k forks source link

[ANDROID] $cordovaPushV5:notificationReceived is not triggered when app is in background #1554

Closed ronaiza-cardoso closed 7 years ago

ronaiza-cardoso commented 7 years ago

Expected Behaviour

When I send a push notification and the APP is already opened, the tsb.selectIndex change the value to o. The "data.additionalData.foreground" is true.

When I send a push notification and the APP is in background, show the notification in android notify. If I tap this notification, open the APP and show the same value to tsb.selectIndex that was when I leave the APP. I expected that when the APP was in background and recived the messages he should update the tsb.selectIndex

Actual Behaviour

my code is When I send a push notification and the APP is active, that's all right. When I send a push notification and the APP is in background, I receive the notification, but it open only the APP without update my variable. I have checked that the event is have fired cause I can see the console.log

Steps to Reproduce

Build android: cordova run android the apk is stated on my device send notification through my web application recive the notification tap on notificatin and open the app

Platform and Version (eg. Android 5.0 or iOS 9.2.1)

Android 6.0

(Android) What device vendor (e.g. Samsung, HTC, Sony...)

Moto G4 plus

Cordova CLI version and cordova platform version

cordova --version                                             # e.g. 6.4.0
cordova platform version android                     # e.g. 6.0.0

Plugin version

cordova plugin version | grep phonegap-plugin-push   # e.g. 1.6.0

Sample Push Data Payload

 function getPushData(message, devices) {
   if (!devices.length) {
     return [];
   }

   const ids = devices.map(device => device.device_id);
   return {
     "devices" : ids,
     "title" :   message.sender_name,
     "message" : message.text,
     "sound" :   true,
    "badge" :   "2",
    "payload" : [{"type" : "notification"}],
    "notId" : message._id
  };
};

Sample Code that illustrates the problem

$rootScope.$on('$cordovaPushV5:notificationReceived', (event, data) => {
  console.log(data);
  if (data.additionalData.foreground === false) {
    tsb.selectedIndex = 0;
  }
});

Logs taken while reproducing problem

N/A because I don't know how to see console logs generated from app when it is on background. When he is on foreground I can see the logs thought chrome://inspect/#devices

macdonst commented 7 years ago

@yesroh are you sure you are getting into the if statement? Can you put a console.log in there to see that the tsb.selectedIndex = 0; line is being executed? Also, I'm not sure how your code works but your UI may be updated first then the tab selected gets set to 0.

ronaiza-cardoso commented 7 years ago

yes, I'm sure. The value inside of the if is changed when the app is in foreground and I have this code

$rootScope.$on('$cordovaPushV5:notificationReceived', (event, data) => {
  console.log(data);
  if (data.additionalData.foreground === true) {
    tsb.selectedIndex = 0;
  }
});
macdonst commented 7 years ago

@yesroh yes but when the notification is received your app is in the background so the check:

if (data.additionalData.foreground === true)

should fail and your update of the selectedIndex will never happen. You can check the value by adding a console.log(data.additionalData.foreground); as it should be false when your app is in the background and you click on the notification to start the app.

ronaiza-cardoso commented 7 years ago

yes, I know that. What I need is that the value change when the app is false. But it is not happen

macdonst commented 7 years ago

@yesroh so the plugin is working like it should. If you want the incoming push notification to always update your selectedIndex you'll need to stop checking the data.additionalData.foreground value.

Scenarios:

1) App in foreground

Push notification is received by the app, the $cordovaPushV5:notificationReceived event handler is received and data.additionalData.foreground is true.

2) App in background

Push notification is received by the OS, then the user clicks on the notification. The app starts and the $cordovaPushV5:notificationReceived event handler is received and data.additionalData.foreground is false.

Make sense?

ronaiza-cardoso commented 7 years ago

uhhh! yes! The event $cordovaPushV5:notificationReceived is just fired when the app is open?! so when the user tap on notification and open the app the value should change, rigth?

macdonst commented 7 years ago

@yesroh the value of data.additionalData.foreground is set when the notification is received. If the app is in the foreground it is true, if it is in the background it is false. This value does not change when you start the app by clicking on a push notification to bring the app to the foreground. Instead it is used in the notification handler to determine if the push arrived when the app was in the foreground or not.

ronaiza-cardoso commented 7 years ago

ok, so when the app is in background he could not chande the value? if not, do you know some way of doing that? thanks for the help

fredgalvao commented 7 years ago

@yesroh O que o Simon quis dizer, é que a flag foreground vai estar false quando o app estiver em background, e é por isso que seu código dentro do if não está sendo executado: você pediu pra que ele não fosse executado quando foreground === false :wink: .

Se você quer que a variável seja atualizada SEMPRE, tanto quando o app estiver ativo quanto quando ele estiver inativo (em background ou completamente fechado) então você precisa remover a condição completamente, e executar a atualização da variável em todos os casos.

Sobre sua pergunta de se o evento é disparado apenas quando o app está ativo: não, o evento é disparado sempre que possível. Isso inclui casos como:

ronaiza-cardoso commented 7 years ago

I need the variable to be updated ONLY when foreground === false and this is not happening

fredgalvao commented 7 years ago

Well, your code is demanding it not to happen:

$rootScope.$on('$cordovaPushV5:notificationReceived', (event, data) => {
  console.log(data);
  if (data.additionalData.foreground === true) {
    tsb.selectedIndex = 0;
  }
});

How do you want it to run on foreground === false when your condition says data.additionalData.foreground === true?

ronaiza-cardoso commented 7 years ago

do you read the main question? on this by default I have data.additionalData.foreground === false. I have put then true just to see if the value change, and in foreground works like I expected. But when is in background don't work. I solve my problem using another plugin to my app work on background. I'm using this plugin with other to works like I want. Thank's for the help!

macdonst commented 7 years ago

@yesroh what is the value of data.additionalData.foreground when your app is in the background then you click on the notification? I'm really confused at this point.

ronaiza-cardoso commented 7 years ago

I can not see the value of data.additionalData.foreground when the app is in background

macdonst commented 7 years ago

@yesroh I mean after you get the push notification, you click on the notification in the device shade which starts your app and fires the $cordovaPushV5:notificationReceived event. What is the value of data.additionalData.foreground when the event is fired?

fredgalvao commented 7 years ago

I can not see the value of data.additionalData.foreground when the app is in background

Do you mean that the console.log(data); at the root of your notification handler is NOT executed when you click on the notification sent when the application is on the background?

macdonst commented 7 years ago

@fredgalvao I wonder if @yesroh is sending all the push notification stuff in notification and not `data.

Have you read https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/PAYLOAD.md#notification-vs-data-payloads

ronaiza-cardoso commented 7 years ago

my config:

{
    "devices" : ids, 
    "title" :   message.sender_name,
    "message" : message.text,
    "sound" :   true,
    "content-available": "1", // Receive notification in background.
    "vibrationPattern" : [300, 150, 300], // Vibrate for 300ms then wait 150ms and then vibrate for 300ms.
    "badge" :   "2",
    "notId" : message._id,
    "payload" : { // Payload for client processing.
      "conversationId": message._id,
      "type": "notification"
    }
  }

and what I recived from my backend:

macdonst commented 7 years ago

@yesroh how are you sending the push payload? Because that format does not look right.

ronaiza-cardoso commented 7 years ago

sorry about the thread, only reading and rereading the documentation and having access to the push server is that I saw that the data was being sent correctly, but the push did not interpret them. So I put the right filds to receive.

macdonst commented 7 years ago

@yesroh so I can close this issue?

ronaiza-cardoso commented 7 years ago

Sure! Thank you for the help.

amangoyalgoyal commented 6 years ago

HI, I am implementing same code but i didn't any ntification when my app is in foreground, can you please tell me where i am wrong, i am posting my code below:

$cordovaPushV5.initialize(
            {
                android: {
                    senderID: "951079272607"  //fcm
                   //senderID : "402556160618" //gcm
                }
            }
        ).then(function (result) {
            $cordovaPushV5.onNotification();
             $cordovaPushV5.onError();
            console.log("About to register");
            $cordovaPushV5.register().then(function (device_token) {
                console.log("Register success with device_token " + device_token);

                //registerDevice();
            }, function (err) {
                // handle error
                console.log("Error registering device");
            });
        });

        $rootScope.$on('$cordovaPushV5:notificationReceived', function(event, notification) {
            //Never reaches here for Android in background, but works fine for iOS when in background
            //Reaches here for Android when in foreground
console.log("jsjsadsa")
           console.log('Received some notification: '+ JSON.stringify([notification]));

            $cordovaPushV5.finish().then(function (result) {
                console.log('finished notificationReceived RESULT: ' + result);
            }, function (err) {
                // handle error
                console.log('finished notificationReceived ERROR: ' + err);

            });
        });

        $rootScope.$on('$cordovaPushV5:errorOccurred', function(event, error) {
            // handle error
            console.log('cordovaPushV5:errorOccurred ERROR: ' + error);
        });
}]);
lock[bot] commented 6 years ago

This thread has been automatically locked.