6
votes

How can we get GCM push notifications in a phonegap android application even when the app goes idle or is in background.

"katzer/cordova-plugin-background-mode" doesn't seems to work...

"I'am getting the push notifications successfully when the app runs foreground"

cordova version:4.3.0 android 4.4 phonegap 4.2.0

I'll copy my notification functions below... on deviceready

function onDeviceReady() {

        try 
            {
                      pushNotification = window.plugins.pushNotification;
              jQuery("#app-status-ul").append('<li>registering ' + device.platform + '</li>');
                      if (device.platform == 'android' || device.platform == 'Android' ||
                                device.platform == 'amazon-fireos' ) {
            pushNotification.register(successHandler, errorHandler, {"senderID":"my-project-id","ecb":"onNotification"});   
              } else {
                          pushNotification.register(tokenHandler, errorHandler, {"badge":"true","sound":"true","alert":"true","ecb":"onNotificationAPN"});  // required!
                      }
            }
        catch(err) 
            { 
              txt="There was an error on this page.\n\n"; 
              txt+="Error description: " + err.message + "\n\n"; 
              alert(txt); 
            } 
        }

and

function onNotification(e) {

            switch( e.event )
            {
                case 'registered':


      if ( e.regid!='' )
      {

           android_reg_id =  e.regid;


          jQuery.ajax({
            type:"POST",
            url:SITEURL+"index.php?r=Manageuser/App_Reg_Android",
            data:{regid: android_reg_id,employeeno:employeeno}
        }).done(function(msg) {

        });             

      }
                break;                    
                case 'message':
                  // if this flag is set, this notification happened while we were in the foreground.
                  // you might want to play a sound to get the user's attention, throw up a dialog, etc.
                  if (e.foreground)
                  {                      
               //jQuery("#app-status-ul").html('<li>MESSAGE -> MSG: ' + e.payload.message + '</li>');
                // on Android soundname is outside the payload. 
                      // On Amazon FireOS all custom attributes are contained within payload
                      var soundfile = e.soundname || e.payload.sound;
                      // if the notification contains a soundname, play it.
                      // playing a sound also requires the org.apache.cordova.media plugin
                      var my_media = new Media("/www/"+ soundfile);

                      my_media.play();
                   }
        else
        {


               if (e.coldstart)
                    $("#app-status-ul").append('<li>--COLDSTART NOTIFICATION--' + '</li>');
               else
                    $("#app-status-ul").append('<li>--BACKGROUND NOTIFICATION--' + '</li>'); 
                    //location.href = e.payload.redid;
        // otherwise we were launched because the user touched a notification in the notification tray.

        }

          jQuery("#app-status-ul").html('<li>MESSAGE -> MSG: ' + e.payload.message + '</li>');        
        //window.localStorage.setItem("push_que", e.payload.redid);
        //location.href = e.payload.redid;

        break;

                case 'error':
        jQuery("#app-status-ul").append('<li>ERROR -> MSG:' + e.msg + '</li>');
                break;

                default:
        jQuery("#app-status-ul").append('<li>EVENT -> Unknown, an event was received and we do not know what it is</li>');
                break;
            }
        }

Plugin that is used is com.phonegap.plugins.PushPlugin 2.4.0 "PushPlugin"

2
no problems with push notifications, but it doesn't work when app goes idle.....SUJU FE
Running Cordova apps in Background is what it requires. but don't know how!SUJU FE
I don't know if you solve your problem, but I have a similar one. It turns out that my cordova plugin doesn't receive push notifications in the background unless the notification has a "message" attribute. Maybe that's the same problem you are having. This is my question.David Prieto

2 Answers

2
votes

I'm not sure which plugin you are using to catch the Push Notification but I would recommend you use the phonegap-build/PushPlugin. It has a handler which catches the Notifications when the app is opened, in the background or closed. If you press on the Notification it will open your app.

To use the plugin just put this in your code:

var pushNotification;

document.addEventListener("deviceready", function(){
    pushNotification = window.plugins.pushNotification;
    if ( device.platform == 'android' || device.platform == 'Android' ){
        pushNotification.register(
        successHandler,
        errorHandler,
        {
            "senderID":"replace_with_sender_id",
            "ecb":"onNotification"
        });
    }
    //the rest of your deviceReady function
});

// result contains any message sent from the plugin call
function successHandler (result) {
    alert('result = ' + result);
}

// result contains any error description text returned from the plugin call
function errorHandler (error) {
    alert('error = ' + error);
}

Now we have set an instance of the plugin to the global variable pushNotification and an if-statement that registers your android device with the GCM service but you need to place the senderID of your Google API Project here: "senderID":"replace_with_sender_id". If the device was successfully registered it will call the function onNotification. That function should do something like this:

function onNotification(e) {
    console.log('event received: '+e.event);

    switch( e.event )
    {
    case 'registered':
        if ( e.regid.length > 0 )
        {
            //Here you should call a function that sends the registration-ID
            //to your server so you can save it and send push notifications to your device
            console.log("regID = " + e.regid);
        }
    break;

    case 'message':
        if ( e.foreground )
        {
            //App was open when the notification was received
            console.log('foreground');
            // on Android soundname is outside the payload.
            var soundfile = e.soundname || e.payload.sound;
            // if the notification contains a soundname, play it.
            var my_media = new Media("/android_asset/www/"+ soundfile);
            my_media.play();
        }
        else
        {   
            if ( e.coldstart )
            {
                //App was closed
                console.log('coldstart');
            }
            else
            {
                //App was open in the background
                console.log('background');
            }
        }
       alert('message: '+e.payload.message);
    break;

    case 'error':
        alert('GCM error: '+e.msg);
    break;

    default:
        alert('An unknown event has occurred');
    break;
  }
}

This function receives an event from the GCM service which tells it what to do. If the device was registered it logs the device registration-ID in the console and if a message was received it checks if the app is open, closed or open in the background and it will alert the message alert('message: '+e.payload.message);.

Since you are using Android I have just included the code for Android. I hope this is what you were looking for.

2
votes

Receiving push notifications does not require the app to be running in the background.

The Cordova Push Plugin
I recommend this plugin: https://github.com/phonegap-build/PushPlugin for receiving push notifications (when the app is not running).
The documentation on that page is pretty good.
The plugin supports iOS, Android, and other platforms.

Server-side options
I don't know what you are running on the server, and it doesn't actually sound like you necessarily have any problems on the server end, but in the interests of providing a more complete (and more general) cordova push solution answer, I want to mention this:
For Android GCM push messaging check out https://www.npmjs.com/package/node-gcm
And for iOS APN push messaging there is https://github.com/argon/node-apn
I've included these links because, even if you are not running node on the server, the documentation on these pages is a great starting point and they both have links out to more really useful info.

----- Update 4/12/2015 -----

The plugin recommended above has been deprecated, the replacement plugin, https://github.com/phonegap/phonegap-plugin-push, has a much simpler interface.
This simple example of the client-side code has everything you need for most use cases : https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/EXAMPLES.md