首页 文章

当应用程序处于空闲状态或处于后台时,如何获取cordova android推送通知?

提问于
浏览
5

即使应用程序空闲或处于后台,我们如何才能在 phonegap android 应用程序中获得 GCM push notifications .

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

“当应用程序运行前景时,我成功获得推送通知”

cordova版本:4.3.0 android 4.4 phonegap 4.2.0

我将复制下面的通知功能......在 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;
            }
        }

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

2 回答

  • 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);
    }
    

    现在我们已经将插件的实例设置为全局变量 pushNotification ,并将if语句设置为使用GCM服务注册您的Android设备,但是您需要在此处放置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;
      }
    }
    

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

    由于您使用的是Android,我刚刚提供了Android代码 . 我希望这就是你要找的东西 .

  • 2

    接收推送通知不需要应用程序在后台运行 .

    The Cordova Push Plugin
    我推荐这个插件: https://github.com/phonegap-build/PushPlugin 用于接收推送通知(当应用程序未运行时) .
    该页面上的文档非常好 .
    该插件支持iOS,Android和其他平台 .

    Server-side options
    我实际上听起来你在服务器端一定有任何问题,但为了提供更完整(更通用)的cordova推送解决方案答案,我想提一下:
    对于Android GCM推送消息,请查看https://www.npmjs.com/package/node-gcm
    对于iOS APN推送消息,有https://github.com/argon/node-apn
    我已经包含了这些链接,因为即使你没有在服务器上运行节点,这些页面上的文档也是一个很好的起点,它们都有更多真正有用信息的链接 .

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

    上面推荐的插件已被弃用,替换插件 https://github.com/phonegap/phonegap-plugin-push 具有更简单的界面 .
    这个客户端代码的简单示例包含大多数用例所需的一切:https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/EXAMPLES.md

相关问题