简体   繁体   中英

phonegap-plugin-push not triggering callback function for new notification when app is in foreground

I'm writing a mobile app for Android using Phonegap (cli v5.3.6) and I'm using phonegap-plugin-push v1.3 for registering the device with GCM and handling the notifications as they arrive at the device.

// define the push settings
var push = PushNotification.init({
    "android": {
        "senderID": "*********"
    },
    "ios": {},
    "windows": {}
});

push.on("notification", function(data) {
    console.log("notification received while in app");
    console.log(JSON.stringify(data));
    addMessageToLocalDB(data, false);
});
push.on("error", function(e) {
    console.log(JSON.stringify(e));
});

It works well when the app is either closed or in the background. My problem occurs when the app is in the foreground. I'm looking at the logcat and see that the notification is received, but I'm not seeing my logging to show that the callback function is fired (and obviously, the outcome I'm expecting to see isn't happening). I'm also not seeing the callback function of the error event firing, so it probably isn't really failing.

Am I missing something? I couldn't find anything online about this problem and I can't really read java to understand how the plugin is supposed to behave...

  • Edit: I just figured out something. The logs that indicate on the arrival of the push notification occur even if I remove the code from my javascript - the PushNotification init and on("notificataion") functions. I'm therefore finding myself a bit confused as to where I need to place the init and event handler functions.

My app consists of index.html (which is the page that loads when the app starts) and many other html files (which each act as a separate page of the app. Shouldn't I put the event handler on each individual page? That what I did try...

Thanks, Yosi.

You might need to wait for the deviceready event, before calling PushNotification.init . This might be more reliable (and quicker) than using setTimeout .

I might not get your questuion but if you want to show notification when the app is in foreground .The default value for forceshow parameter is false and you are right it's n't failing

"android": { "senderID": "*********", "forceShow" : "true" },

I eventually noticed that the PushNotification object is sometimes undefined when I first load the page, but then if I wait enough time (100ms), it is then defined. What I ended up doing is an interval to run every 100ms, check if the PushNotification object is defined and if so, run my init+event listener code and clear the interval. This seems to be working well for quite some time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM