Ich implementiere Push-Benachrichtigung in einer Phonegap Android App. Ich folge dem Tutorial here. Im Tutorial sieht die onDeviceready Funktion wie folgt aus:Umgang mit Push-Benachrichtigung in Android PhoneGap App
onDeviceReady: function() {
app.receivedEvent('deviceready');
var pushNotification = window.plugins.pushNotification;
pushNotification.register(app.successHandler, app.errorHandler,{"senderID":"836557454855","ecb":"app.onNotificationGCM"});
},
Das bedeutet, dass jedes Mal, wenn die App startet, ist es für Push-Benachrichtigung mit Google registriert ist. Ich nehme an, dass dies nur einmal getan werden muss. So in dir, ich habe:
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"});
}
}
}
Dann in onNotificationGCM, ich lokale Speicher so eingestellt, dass das Gerät nicht wieder registriert ist:
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;
}
},
Das Problem tritt auf, wenn das Telefon eine neue Push-Benachrichtigung erhält. Wenn der Benutzer im ursprünglichen Projekt aus dem Lernprogramm auf die Benachrichtigung klickt, wird die App geöffnet und der Benutzer sieht die Warnung: "message = blachblah msgcnt = blahblah". Dies liegt daran, dass der Code im Fall "message" in onNotificationGCM() ausgeführt wird.
In meiner App wird die App geöffnet, aber der Code im Fall "Nachricht" wird nicht ausgeführt. Dies liegt daran, dass ich in onDeviceReady() das Gerät nur einmal bei Google registriere. Wenn ich die Bedingung entferne:
if(typeof(device_id)==='undefined' || device_id===null){
und registrieren Sie das Gerät jedes Mal, der Fall "Nachricht" wird ausgeführt. Das scheint jedoch falsch zu sein, um das Gerät jedes Mal in onDeviceReady() registrieren zu müssen. Gibt es eine andere Lösung?