在Android Phonegap应用中处理推送通知消息

use*_*672 6 android cordova

我正在Phonegap Android应用中实现推送通知.我在这里按照教程.在本教程中,onDeviceready函数如下所示:

onDeviceReady: function() {
    app.receivedEvent('deviceready');
    var pushNotification = window.plugins.pushNotification;
    pushNotification.register(app.successHandler, app.errorHandler,{"senderID":"836557454855","ecb":"app.onNotificationGCM"});
},
Run Code Online (Sandbox Code Playgroud)

这意味着每次应用启动时,都会向Google注册推送通知.我认为这只需要做一次.所以在我的作品中,我有:

onDeviceReady: function() {

        var device_id = window.localStorage.getItem('mountmercy_device_id');

        //if device_id is in local storage, then it means registration 
        // with google has already taken place. If not, then register
        if(typeof(device_id)==='undefined' || device_id===null){

            var pushNotification = window.plugins.pushNotification;
            if (window.device.platform == 'android' || window.device.platform == 'Android') {
                pushNotification.register(app.successHandler, app.errorHandler,{"senderID":"475226855592","ecb":"app.onNotificationGCM"});                        
            }
            else{
                //so its apple
                 pushNotification.register(app.tokenHandler,app.errorHandler,{"badge":"true","sound":"true","alert":"true","ecb":"app.onNotificationAPN"});
            }

        } 

}
Run Code Online (Sandbox Code Playgroud)

然后在onNotificationGCM中,我设置了本地存储,因此设备未再次注册:

onNotificationGCM: function(e) {

    switch( e.event )
    {
        case 'registered':
            if ( e.regid.length > 0 )
            {
                  /*
                   save reg id to server and store response in local storage
                   ...
                   ...
                   ...
                  */

                  window.localStorage.setItem('mountmercy_device_id', data.id);
                  window.localStorage.setItem('mountmercy_api_key', data.get('api_key'));

            }
            break;

        case 'message':
            // this is the actual push notification. its format depends on the data model from the push server
            alert('message = '+e.message+' msgcnt = '+e.msgcnt);

            break;

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

        default:
           // alert('An unknown GCM event has occurred');
            break;
    }
}, 
Run Code Online (Sandbox Code Playgroud)

手机收到新的推送通知时会出现此问题.在本教程的原始项目中,当用户单击通知消息时,应用程序将打开,用户将看到警报:"message = blachblah msgcnt = blahblah".这是因为onNotificationGCM()中"message"情况下的代码被执行.

在我的应用程序中,应用程序打开,但"消息"案例中的代码未执行.这是因为,在onDeviceReady()中,我只向Google注册一次设备.如果我删除条件:

if(typeof(device_id)==='undefined' || device_id===null){
Run Code Online (Sandbox Code Playgroud)

并且每次注册deice,执行"message"情况.但是每次在onDeviceReady()中注册设备似乎都是错误的.还有其他解决方案吗?

use*_*672 3

我在 Google Cloud Messaging 的文档中看到它说

Google 可能会定期刷新注册 ID

在这种情况下,我每次打开应用程序时都会向 Google 注册,并更新返回的注册 ID,以防它发生更改。这也解决了在通知栏中单击推送消息时处理推送消息的问题。