当应用处于空闲状态或处于后台时,如何获取Cordova Android推送通知?

SUJ*_*M U 5 android cordova

即使应用处于闲置状态或处于后台,我们如何在phonegap android应用中获取GCM 推送通知

“ katzer / cordova-plugin-background-mode”似乎不起作用...

当应用程序运行在前台时,我成功获得了推送通知

科尔多瓦版本:4.3.0 android 4.4 phonegap 4.2.0

我会复制下面我通知功能......上deviceready

函数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); 
            } 
        }
Run Code Online (Sandbox Code Playgroud)

函数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;
            }
        }
Run Code Online (Sandbox Code Playgroud)

使用的插件是com.phonegap.plugins.PushPlugin 2.4.0“ PushPlugin”

Tim*_*imo 2

我不确定您使用哪个插件来捕获推送通知,但我建议您使用phonegap-build/PushPlugin。它有一个处理程序,可以在应用程序打开、在后台或关闭时捕获通知。如果您按通知,它将打开您的应用程序。

要使用该插件,只需将其放入您的代码中:

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);
}
Run Code Online (Sandbox Code Playgroud)

现在我们已经将插件的实例设置为全局变量pushNotification和一个 if 语句,该语句将您的 Android 设备注册到 GCM 服务,但您需要将 Google API 项目的 senderID 放在这里:"senderID":"replace_with_sender_id"。如果设备注册成功,它将调用该函数onNotification。该函数应该执行如下操作:

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

该函数从 GCM 服务接收一个事件,该事件告诉它要做什么。如果设备已注册,它会在控制台中记录设备注册 ID,如果收到消息,它会检查应用程序是否打开、关闭或在后台打开,并会提醒该消息alert('message: '+e.payload.message);

由于您使用的是 Android,所以我刚刚包含了 Android 的代码。我希望这就是您正在寻找的。