2015-08-22 2 views
-1

Несмотря на все попытки и рассмотрение предыдущих вопросов и решений по SO, я не могу получить идентификатор registrationID из GCM.Невозможно получить идентификатор регистрации из GCM

Я использую pushplugin и пытаюсь построить для Android с помощью Cordova. Приложение успешно построено, но, похоже, функции onNotificationGCM в них никогда не вызываются. Вызывается обработчик успеха. Я использую симулятор Android Genymotion.

О проблемах с github Некоторые утверждают, что придают функции onNotification объекту окна. Но я тоже не мог сделать эту работу. Есть ли общая проблема. Кто-нибудь использует этот плагин успешно?

Что может быть причиной этого? В этом испытании используется другой плагин cordova, отличный от указанного выше. Хотя я пробовал пример в приведенном выше плагине github repo, это не сработало.

index.js:

var app = { 
    // Application Constructor 
    initialize: function() { 
     this.bindEvents(); 
    }, 
    // Bind Event Listeners 
    // 
    // Bind any events that are required on startup. Common events are: 
    // 'load', 'deviceready', 'offline', and 'online'. 
    bindEvents: function() { 
     document.addEventListener('deviceready', this.onDeviceReady, false); 
    }, 
    // deviceready Event Handler 
    // 
    // The scope of 'this' is the event. In order to call the 'receivedEvent' 
    // function, we must explicity call 'app.receivedEvent(...);' 
    // "senderID":"273794328096" 
    onDeviceReady: function() { 
     app.receivedEvent('deviceready'); 
    }, 
    // Update DOM on a Received Event 
    receivedEvent: function(id) { 
     console.log('Received Event: ' + id); 
     if (device.platform == 'android' || device.platform == 'Android') { 
      alert("Register called"); 
      window.GcmPushPlugin.register(app.successHandler, app.errorHandler, { 
       "senderId":"273794328096", 
       "jsCallback":"onNotificationGCM" 
      }); 
     } 
     else { 
      alert("Register called"); 
      pushNotification.register(this.successHandler,this.errorHandler,{"badge":"true","sound":"true","alert":"true","ecb":"onNotificationAPN"}); 
     } 
    }, 
    // result contains any message sent from the plugin call 
    successHandler: function(result) { 
     alert('Callback Success! Result = '+ result.gcm) 
    }, 
    errorHandler:function(error) { 
     alert("Error:" + error); 
    }, 
}; 

function onNotificationGCM(notification) { 
    console.log("Event Received: " + notification); // { "extra": {"url" : "someurl.js" } } 
} 

index.html:

<!DOCTYPE html> 
<html> 
    <head> 
     <meta charset="utf-8" /> 
     <meta name="format-detection" content="telephone=no" /> 
     <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" /> 
     <link rel="stylesheet" type="text/css" href="css/index.css" /> 
     <title>Hello World</title> 
    </head> 
    <body> 
     <script type="text/javascript" src="cordova.js"></script> 
     <script type="text/javascript" src="js/index.js"></script> 
     <script type="text/javascript"> 
      app.initialize(); 
     </script> 
    </body> 
</html> 
+1

Предложите вам попробовать образец кода клиента GCM от GitHub – BNK

+0

Я пробовал три из них. но они не работают. –

+0

@Huey добавил соответствующий код сейчас. –

ответ

0

Пример кода

var Project = {}; 

var app = { 
    initialize: function() { 
     this.bindEvents(); 
    }, 

    bindEvents: function() { 
     document.addEventListener('deviceready', this.onDeviceReady, false); 
    }, 

    onDeviceReady: function() { 
     app.receivedEvent('deviceready'); 
    }, 

    receivedEvent: function(id) { 
     app.registerDevice(); 
    }, 

    registerDevice: function(){ 
     if (window.cordova && window.cordova.platformId=='android'){ 
      try{ 
       var pushNotification = window.plugins.pushNotification; 
       pushNotification.register(
        app.successPN, 
        app.errorPN, 
        { 
         "senderID": "727700427600", 
         "ecb": "Project.Notification" 
        } 
       ); 
      } 
      catch (ex){ 
       // window.alert('Error (message): ' + ex.message); 
       // window.alert('Error (stack): ' + ex.stack); 
      } 
      console.log("regID = " + localStorage['pioneer.device.regid']); 
     } 
    }, 
    successPN: function (result){ 
     // window.alert('PN Success: ' + result); 
    }, 
    errorPN: function (result){ 
     // window.alert('PN Error: ' + result); 
    } 
}; 

app.initialize(); 

Project.Notification

Project.Notification = function(e){ 
    // Pioneer.alert(JSON.stringify(e), 'alert'); 
    switch(e.event) 
    { 
     case 'registered': 
      // process reg id 
      break;     
     case 'message': 
      // print message 
      break; 
     case 'error': 
      // window.alert("Notification error: " + e.msg); 
      break; 
     default: 
      // window.alert("Notification - Unknown event"); 
      break; 
    } 
}; 
+0

Ни в коем случае. Это не работает. ı видеть только выходное предупреждение sucessPN, говорящее «ОК». Также, чтобы очистить, я добавил некоторые предупреждения в Project.Notification cases: для каждого типа: \t 'window.alert (" registerId: "+ e.regid +" "+ e.event.regid); window.alert («Уведомляющее сообщение:« + »« + e + »« + e.message + »+ + e.event.message); window.alert ("Ошибка уведомления:" + e.msg); window.alert («Уведомление - неизвестное событие»); ' –

+0

Проблема решена! Теперь я тестирую приложение на реальном устройстве Android, а не на симуляторе. –