我正在为Phonegap Android应用程序实现推送通知。 我正在按照这里的教程进行操作。 在教程中,onDeviceReady函数如下所示:
onDeviceReady: function() {
app.receivedEvent('deviceready');
var pushNotification = window.plugins.pushNotification;
pushNotification.register(app.successHandler, app.errorHandler,{"senderID":"836557454855","ecb":"app.onNotificationGCM"});
},
这意味着每次应用程序启动时,它都会向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"});
}
}
}
接着,在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;
}
},
当手机接收到新的推送通知时,会出现问题。在教程中原始项目中,当用户点击通知消息时,应用程序会打开并且用户会看到警报:“message = blachblah msgcnt = blahblah”。这是因为在onNotificationGCM()函数中“message”情况下的代码被执行。
在我的应用程序中,应用程序已经打开,但是“message”情况下的代码没有被执行。这是因为在onDeviceReady()函数中,我只注册了一次与谷歌的设备。如果我删除条件:
if(typeof(device_id)==='undefined' || device_id===null){
每次执行"message"事件时,都需要重新注册设备,但是在onDeviceReady()中每次都注册设备似乎是不正确的。有其他解决方法吗?