0

Я разрабатываю приложение для получения push-уведомлений, однако у меня есть несколько проблем.Push Notification PhoneGap

Я использую PhoneGap развивать мое приложение и этот плагин - PushPlugin Я установил плагин с помощью PhoneGap успешно и он указан в моих установленных плагинов и у меня есть необходимые разрешения при установке мое приложение на моем телефоне.

Я зарегистрировал свое приложение для сервисов GCM и получил свой номер проекта, ключ API и т. Д. Я выполнил следующие шаги: Google Cloud Messaging.

Когда приложение начнет сначала, мне, очевидно, потребуется получить идентификатор регистрации для моего устройства (устройство Android кстати), однако я не смог заставить его запустить весь регистрационный код.

В документации для плагина говорится, что код необходимо вызвать, как только устройство будет готово - что я и сделал.

var pushNotification; 

document.addEventListener("deviceready", function(){ 
    pushNotification = window.plugins.pushNotification; 

    $("#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":"sender_ID", 
     "ecb":"onNotification" 
    }); 
} 

}); 



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

// Android and Amazon Fire OS 
function onNotification(e) { 
    $("#app-status-ul").append('<li>EVENT -> RECEIVED:' + e.event + '</li>'); 

    switch(e.event) 
    { 
    case 'registered': 
     if (e.regid.length > 0) 
     { 
      $("#app-status-ul").append('<li>REGISTERED -> REGID:' + e.regid + "</li>"); 
      // Your GCM push server needs to know the regID before it can push to this device 
      // here is where you might want to send it the regID for later use. 
      console.log("regID = " + e.regid); 
     } 
    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) 
     { 
      $("#app-status-ul").append('<li>--INLINE NOTIFICATION--' + '</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. 
      var my_media = new Media("/android_asset/www/"+ soundfile); 
      my_media.play(); 
     } 
     else 
     { // otherwise we were launched because the user touched a notification in the notification tray. 
      if (e.coldstart) 
      { 
       $("#app-status-ul").append('<li>--COLDSTART NOTIFICATION--' + '</li>'); 
      } 
      else 
      { 
       $("#app-status-ul").append('<li>--BACKGROUND NOTIFICATION--' + '</li>'); 
      } 
     } 

     $("#app-status-ul").append('<li>MESSAGE -> MSG: ' + e.payload.message + '</li>'); 
      //Only works for GCM 
     $("#app-status-ul").append('<li>MESSAGE -> MSGCNT: ' + e.payload.msgcnt + '</li>'); 
     //Only works on Amazon Fire OS 
     $status.append('<li>MESSAGE -> TIME: ' + e.payload.timeStamp + '</li>'); 
    break; 

    case 'error': 
     $("#app-status-ul").append('<li>ERROR -> MSG:' + e.msg + '</li>'); 
    break; 

    default: 
     $("#app-status-ul").append('<li>EVENT -> Unknown, an event was received and we do not know what it is</li>'); 
    break; 
    } 
} 

При успешном выполнении он должен запускать обработчик успеха или если он не работает, обработчик ошибок. Однако я не получаю ни того, ни другого.

Я сузил код, чтобы увидеть, если он сбой на определенной строке, используя предупреждения. Как показано ниже -

alert('Start of push'); 
document.addEventListener("deviceready", function(){ 
var pushNotification; 
    pushNotification = window.plugins.pushNotification; 
    alert('past pushNotification'); 

    alert(device.platform); 

    $("#app-status-ul").append('<li>registering ' + device.platform + '</li>'); //crashing on this line 

    alert('registering'); 
if(device.platform == 'android' || device.platform == 'Android'){ 
    alert('pushreg'); 
    pushNotification.register(
    successHandler, 
    errorHandler, 
    { 
     "senderID":"sender_ID_here", 
     "ecb":"onNotification" 
    }); 
} 
alert('register complete');  
}); 




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

// Android and Amazon Fire OS 
function onNotification(e) { 
    $("#app-status-ul").append('<li>EVENT -> RECEIVED:' + e.event + '</li>'); 

    switch(e.event) 
    { 
    case 'registered': 
     if (e.regid.length > 0) 
     { 
      $("#app-status-ul").append('<li>REGISTERED -> REGID:' + e.regid + "</li>"); 
      // Your GCM push server needs to know the regID before it can push to this device 
      // here is where you might want to send it the regID for later use. 
      console.log("regID = " + e.regid); 
     } 
    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) 
     { 
      $("#app-status-ul").append('<li>--INLINE NOTIFICATION--' + '</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. 
      var my_media = new Media("/android_asset/www/"+ soundfile); 
      my_media.play(); 
     } 
     else 
     { // otherwise we were launched because the user touched a notification in the notification tray. 
      if (e.coldstart) 
      { 
       $("#app-status-ul").append('<li>--COLDSTART NOTIFICATION--' + '</li>'); 
      } 
      else 
      { 
       $("#app-status-ul").append('<li>--BACKGROUND NOTIFICATION--' + '</li>'); 
      } 
     } 

     $("#app-status-ul").append('<li>MESSAGE -> MSG: ' + e.payload.message + '</li>'); 
      //Only works for GCM 
     $("#app-status-ul").append('<li>MESSAGE -> MSGCNT: ' + e.payload.msgcnt + '</li>'); 
     //Only works on Amazon Fire OS 
     $status.append('<li>MESSAGE -> TIME: ' + e.payload.timeStamp + '</li>'); 
    break; 

    case 'error': 
     $("#app-status-ul").append('<li>ERROR -> MSG:' + e.msg + '</li>'); 
    break; 

    default: 
     $("#app-status-ul").append('<li>EVENT -> Unknown, an event was received and we do not know what it is</li>'); 
    break; 
    } 
} 
alert('end of push'); 

Очевидно, что в состоянии запустить первое предупреждение «Пуск нажима», а также «прошлое Push Notification» предупреждение. Я проверил, чтобы убедиться, что device.platform не сбил его и не включил оповещение с тем же кодом, который возвращает Android на моем устройстве. Однако я никогда не кажется, чтобы получить что-либо после того, как та, которая заставляет меня верить, что это сбой на $("#app-status-ul").append('<li>registering ' + device.platform + '</li>');

Если кто-то может помочь мне попытаться понять это, что было бы большим подспорьем,

Спасибо.

+0

принять ответ если помогло! – Arti

ответ

0

Чтобы получить платформу устройства, «Устройство» плагин должен быть установлен на вашем приложении Phonegap/Cordova.

Вы можете добавить плагин в приложение из командной строки, как этот

cordova plugin add org.apache.cordova.device 

в список плагинов

cordova plugin ls 

Если ваш получают [ «org.apache.cordova.устройство»] в списке, это означает, что ваш плагин не установлен

Для удаления Plugin

cordova plugin rm org.apache.cordova.device 
+0

Привет, У меня уже установлены все зависимые плагины. Оба устройства и носители. – Jack

+0

попробуйте удалить плагин устройства и снова установить его снова. Если проблема не устранена, попробуйте удалить «Push Plugin» из приложения и снова установить его снова. –

0

Это шаги, которые необходимо выполнить, чтобы создать приложение для нажимного уведомления:

* Установить Cordova с помощью интерфейса командной строки и команд пуска следующим образом (см link)

1) Создать проект Cordova

cordova create hello com.example.hello HelloWorld 

2) Добавить Платформа

cordova platform add android 

3) Построить проект

cordova build android 

4) Добавить плагины

cordova plugin add org.apache.cordova.device 
cordova plugin add org.apache.cordova.media 
cordova plugin add https://github.com/phonegap-build/PushPlugin.git 

5) Построить проект

cordova build android 

6) Imp ort созданный проект в Eclipse

7) Используйте необходимый код от this, чтобы создать свой index.html.

8) Скопировать PushNotification.js из

ProjectFolderPath \ Plugins \ com.phonegap.plugins.PushPlugin \ WWW

ProjectFolderPath -path проекта, созданного с использованием CLI

Вашему проекту eclipse assets/www/ Папка

9) Также добавьте файл jquery .js и звуковой файл в папку assets/www. (Вы можете скачать и скопировать его из Github Пример папки)

10) В index.html не забудьте изменить SenderId вашего GCM проекта (т.е. ProjectID)

11) Выполнить приложение на реальном устройстве. Это может не сработать на эмуляторе.