Я следил за этим образцом, чтобы получать push-уведомления Android (с GCM), работающие на эмуляторе Android. После $cordovaPush.register(config)
я получаю "ОК" в качестве ответа. Но он никогда не запускает мой обратный вызов [$scope.$on('$cordovaPush:notificationReceived'
]. И, как следствие, я никогда не получаю регистрационный идентификатор.
Я создал проект Google API. И я использую этот идентификатор проекта в config.senderID при вызове $cordovaPush.register(config)
.
Я также зарегистрировал учетную запись Gmail в своем эмуляторе.
Думаю, у меня 2 вопроса.
1.Можно ли получать (и регистрировать) push-уведомления на эмуляторе Android?
почему я не получаю событие $ cordovaPush: notificationReceived, которое вызывает мой обратный вызов?
app.controller ('AppCtrl', function ($ scope, $ cordovaPush, $ cordovaDialogs, $ cordovaMedia, $ cordovaToast, ionPlatform, $ http) { $ scope.notifications = [];
// call to register automatically upon device ready ionPlatform.ready.then(function (device) { $scope.register(); }); // Register $scope.register = function () { var config = null; if (ionic.Platform.isAndroid()) { config = { "senderID": "12834957xxxx" }; } $cordovaPush.register(config).then(function (result) { console.log("Register success " + result); $cordovaToast.showShortCenter('Registered for push notifications'); $scope.registerDisabled=true; }, function (err) { console.log("Register error " + err) }); } $scope.$on('$cordovaPush:notificationReceived', function (event, notification) { console.log(JSON.stringify([notification])); if (ionic.Platform.isAndroid()) { handleAndroid(notification); } }); // Android Notification Received Handler function handleAndroid(notification) { // ** NOTE: ** You could add code for when app is in foreground or not, or coming from coldstart here too // via the console fields as shown. console.log("In foreground " + notification.foreground + " Coldstart " + notification.coldstart); if (notification.event == "registered") { $scope.regId = notification.regid; storeDeviceToken("android"); } else if (notification.event == "message") { $cordovaDialogs.alert(notification.message, "Push Notification Received"); $scope.$apply(function () { $scope.notifications.push(JSON.stringify(notification.message)); }) } else if (notification.event == "error") $cordovaDialogs.alert(notification.msg, "Push notification error event"); else $cordovaDialogs.alert(notification.event, "Push notification handler - Unprocessed Event"); }
4 ответа
У меня та же проблема. Об этом сообщалось в github ngCordova, но ответа пока нет.
Мне удалось это исправить. Я знаю, что это не лучшее решение, если вы используете angular, но это единственный способ узнать идентификатор регистра.
Внутри объекта конфигурации вы должны указать
'ecb'
:var androidConfig = { "senderID": "388573974286", "ecb": "function_to_be_called" };
Вынесите за пределы контроллера функцию:
window.function_to_be_called = function (notification) {
switch(notification.event) {
case 'registered':
if (notification.regid.length > 0 ) {
alert('registration ID = ' + notification.regid);
}
break;
case 'message':
// this is the actual push notification. its format depends on the data model from the push server
alert('message = ' + notification.message + ' msgCount = ' + notification.msgcnt);
break;
case 'error':
alert('GCM error = ' + notification.msg);
break;
default:
alert('An unknown GCM event has occurred');
break;
}
};
Обновите свой ng-cordova.js в lib / ng-cordova.js со страницы http://ngcordova.com/docs / install / в ng-cordova-master \ dist \ ng-cordova.js
Даже если вы обновите название события, как вы сказали, у меня будет еще одна проблема: processmessage failed: message: jjavascript:angular.element(document.queryselector('[ng-app]')).injector().get('$cordovapush').onnotification({"event":"registered"
...
Это происходит, когда angular не находит 'ng-app' и возвращает 'undefined' angular.element(document.querySelector('[ng-app]'))
Чтобы решить эту проблему, вы можете вручную установить 'ecb
' следующим образом:
angular.element(document.body).injector().get('$cordovaPush').onNotification
Благодаря этой записи на ионном форуме < / а>
Исправить это намного проще, чем кажется. Я изменил с:
$scope.$on('$cordovaPush:notificationReceived', function (event, notification) {
Чтобы :
$scope.$on('pushNotificationReceived', function (event, notification) {
Во время отладки я заметил это на ng-cordova.js:
angular.module('ngCordova.plugins.push', [])
.factory('$cordovaPush', ['$q', '$window', '$rootScope', function ($q, $window, $rootScope) {
return {
onNotification: function (notification) {
$rootScope.$apply(function () {
$rootScope.$broadcast('pushNotificationReceived', notification);
});
},
Это означает, что он выполняет широковещательную рассылку для pushNotificationReceived. Не «notificationReceived», как задокументировано.
Похожие вопросы
Новые вопросы
android
Android — это мобильная операционная система Google, используемая для программирования или разработки цифровых устройств (смартфонов, планшетов, автомобилей, телевизоров, одежды, очков, IoT). Для тем, связанных с Android, используйте теги, специфичные для Android, такие как android-intent, android-activity, android-adapter и т. д. Для вопросов, отличных от разработки или программирования, но связанных с Android framework, используйте эту ссылку: https://android .stackexchange.com.