Phonegap Plugin Push & Node-gcm NotRegistered - javascript

So I have seen other people with this issue post on here. Nothing seems to right with what I am having. Here is the steps of my issues:
1) I installed my Ionic app onto my phone.
2) Setup my sender key and API key with the google console.
3) Created my node-gcm server.
4) Sent notifications to my phone using my phonegap-plugin-push device token.
5) uninstalled my app
6) reinstalled the app.
7) tried sending notifications, and now I am getting a NotRegistered Error by GCM.
I cross checked all of my keys: server, sender, device. All are correct. I cannot figure out why after reinstallation of the app, i get a notregistered error. Here are the tools I am using:
Ionic framework, android phone, NodeJS server, Node-gcm, google dev console, phonegap-plugin-push
And lastly, Code:
.run(function($ionicPlatform, $ionicPopup, $rootScope, $http, $state) {
$ionicPlatform.ready(function() {
var push = PushNotification.init({
android: {
senderID: "7821....1490",
sound: "true",
vibration: "true"
},
browser: {
pushServiceURL: 'http://push.api.phonegap.com/v1/push'
},
ios: {
alert: "true",
badge: true,
sound: "true",
vibration: "true",
clearBadge: true
},
windows: {}
});
push.on('registration', function(data) {
console.log("Device Token: " + data.registrationId);
$rootScope.devToken = data.registrationId;
})
var message = new gcm.Message();
message.addData('title', 'Alert');
message.addData('message', 'Message From: '+ messageUser + '\n' + 'Message Text: ' + messageText);
//message.addData('image', image);
sender.send(message, android, function (err, response) {
if(err) {}
else {
console.log(response.results);
//response is NotRegistered, unregister devices
for (var i = 0; i < response.results.length; i++) {
if (response.results[i].error == 'NotRegistered') {
console.log("ERROR");
}
}
}
});
I am willing to work through this with you. Just know, I have checked all keys, and all are the correct keys. When I reinstalled the app, I got a new device token and I am trying to push to that new device token.

OK! FOR ANYONE WITH THIS PROBLEM READ HERE!
With push plugin, on app uninstall. It does not clear all the data. I am storing the device token in a scope variable and storing it in local storage. On app uninstall, go to settings and clear all data before uninstalling. Once you reinstall, you will get a new token and it should work!

Related

plug phonegap-plugin-push to Firebase

Quickly my environment :
Phonegap 8.0.0
phonegap-plugin-push 2.1.2 (the last version is not compatible to phonegap 8.0.0)
At that time :
I manage to receive push notification generated from my local machine via "phonegap push " in the phonegap simulator
I can’t receive push notif from Firebase in the phonegap simulator (is it possible ?)
When I build the app for Android, she crash at start (blank page) due to the phonegap-plugin-push associated code in my app (if I comment it, she start normally)
My code (VueJS framework)
console.log('calling push init');
window.gtvapp.push = PushNotification.init({
'android': {
// 'senderID': 'XXXXXXXX'
},
'browser': {},
'ios': {
'sound': true,
'vibration': true,
'badge': true,
'alert': true
// 'senderID': 'xxxxxxxx'
},
'windows': {}
})
console.log('after init')
window.gtvapp.push.on('registration', function(data) {
console.log('registration event: ' + data.registrationId)
var oldRegId = window.localStorage.getItem('registrationId')
if (oldRegId !== data.registrationId) {
window.localStorage.setItem('registrationId', data.registrationId)
// Post registrationId to your app server as the value has changed
// TODO
}
})
window.gtvapp.push.on('error', function(e) {
console.log('push error = ' + e.message)
})
// (...)
let router = this.$router
window.gtvapp.push.on('notification', function(data) {
console.log('notification event')
console.log(JSON.stringify(data))
if (device.platform === 'Android') {
navigator.notification.alert(
data.message, // message
function() {
console.log(window.location.pathname)
console.log(data.additionalData.path)
// window.localStorage.setItem('pushpath', data.additionalData.path)
router.push(data.additionalData.path)
},
data.title,
'En savoir plus'
)
}
})
This code works perfectly as attended on simulator "phonegap serve" + local push notif "phonegap push "
Questions :
step 1 : is it theoricaly possible to receive Firebase notif in a "phonegap serve instance"
step 2 : is just "google-services.json" file required to correctly configure the firebase registration
Thanks a lot
step 1 : is it theoricaly possible to receive Firebase notif in a "phonegap serve instance"
No it’s not, you have to build the app and install the apk on the device
step 2 : is just "google-services.json" file required to correctly configure the firebase registration
Yes.
Just on thing for phonegap 8 :
<platform name="android">
<resource-file src="google-services.json" target="app/google-services.json" />
</platform>
the "app/" is important.

Pubnub.subscribe not working

I am trying to implement a simple chat in my AngularJs 1.4.5 web app using pubnub.
I am following the steps as given in the pubnub tutorial.
$scope.channel = 'chat_for_trial';
$scope.uuid = 'user1';
Pubnub.init({
publishKey: 'demo',
subscribeKey: 'demo',
uuid: $scope.uuid
});
// Send the messages over PubNub Network
$scope.messageContent = {message: ''};
$scope.sendMessage = function() {
// $scope.messageContent = data;
// Don't send an empty message
if (!$scope.messageContent.message || $scope.messageContent.message === '') {
return;
}
Pubnub.publish({
channel: $scope.channel,
message: {
content: $scope.messageContent.message,
sender_uuid: $scope.uuid,
date: new Date()
},
callback: function(m) {
console.log(m);
}
});
// Reset the messageContent input
$scope.messageContent.message = '';
};
//get messages
$scope.messageContent.messages = [];
// Subscribing to the ‘messages-channel’ and trigering the message callback
Pubnub.subscribe({
channel: $scope.channel,
triggerEvents: ['callback']
});
// Listening to the callbacks
$scope.$on(Pubnub.getMessageEventNameFor($scope.channel), function (ngEvent, m) {
$scope.$apply(function () {
console.log("i am here")
$scope.messageContent.messages.push(m)
});
});
I can send message to the channel chat_for_trial but when checking the occupancy in pubnub console, the subscribed uuid is not listed.
When I sending the message from console it is not displayed in the web app. But data sent from web app can be seen in the pubnub console.
I am working with pubnub: 4.20.1, pubnub-angular: 4.1.0, angularjs: 1.4.5
I would like to know what I am missing here.
The issue was due to the mismatch of the pubnub and pubnub-angular version from the tutorial and the one installed using bower in my application.
The tutorial was for sdk v3 and the current sdk version v4.
Refer this link for working with pubnub sdk v4.

FileOpener2 causing Attempt to invoke virtual method in cordova.js file on Android 6.0 or higher

We use FileOpener2 plugin for cordova to open a downloaded .apk file from our servers. Recently, we found that Android 6.0 or higher devices are throwing an exception only on the file open process. We were able to trace this down to the cordova.js file, where the posted exception occurs. We have yet to find a cause or a fix, but have put a workaround in place. Any info would be amazing on this so we can maintain our in-app self updating process going on all Android devices.
Code (Working on Android <= 6.0):
// we need to access LocalFileSystem
window.requestFileSystem(LocalFileSystem.PERSISTENT, 5 * 1024 * 1024, function (fs) {
//Show user that download is occurring
$("#toast").dxToast({
message: "Downloading please wait..",
type: "warning",
visible: true,
displayTime: 20000
});
// we will save file in .. Download/OURAPPNAME.apk
var filePath = cordova.file.externalRootDirectory + '/Download/' + "OURAPPNAME.apk";
var fileTransfer = new FileTransfer();
var uri = encodeURI(appDownloadURL);
fileTransfer.download(uri, filePath, function (entry) {
//Show user that download is occurring/show user install is about to happen
$("#toast").dxToast({
message: "Download complete! Launching...",
type: "success",
visible: true,
displayTime: 2000
});
////Use pwlin's fileOpener2 plugin to let the system open the .apk
cordova.plugins.fileOpener2.open(
entry.toURL(),
'application/vnd.android.package-archive',
{
error: function (e) {
window.open(appDownloadURL, "_system");
},
success: function () { console.log('file opened successfully'); }
}
);
},
function (error) {
//Show user that download had an error
$("#toast").dxToast({
message: error.message,
type: "error",
displayTime: 5000
});
},
false);
})
Debugging Information:
THIS IS NOT OUR CODE, BUT APACHE/CORDOVA CODE
Problem File: cordova.js
function androidExec(success, fail, service, action, args) {
// argsJson - "["file:///storage/emulated/0/download/OURAPPNAME.apk","application/vnd.android.package-archive"]"
//callbackId - FileOpener21362683899
//action - open
//service FileOpener2
//bridgesecret - 1334209170
// msgs = "230 F09 FileOpener21362683899 sAttempt to invoke virtual method 'android.content.res.XmlResourceParser //android.content.pm.PackageItemInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference"
var msgs = nativeApiProvider.get().exec(bridgeSecret, service, action, callbackId, argsJson);
// If argsJson was received by Java as null, try again with the PROMPT bridge mode.
// This happens in rare circumstances, such as when certain Unicode characters are passed over the bridge on a Galaxy S2. See CB-2666.
if (jsToNativeBridgeMode == jsToNativeModes.JS_OBJECT && msgs === "#Null arguments.") {
androidExec.setJsToNativeBridgeMode(jsToNativeModes.PROMPT);
androidExec(success, fail, service, action, args);
androidExec.setJsToNativeBridgeMode(jsToNativeModes.JS_OBJECT);
} else if (msgs) {
messagesFromNative.push(msgs);
// Always process async to avoid exceptions messing up stack.
nextTick(processMessages);
}

ionic.bundle.js:25642 Error: [$injector:unpr] Unknown provider: $cordovaGeolocationProvider <- $cordovaGeolocation <- AgeCtrl

I am currently in the starting phase of building an app via Ionic. Right now i want to implement the cordova geolocation in it. However this keeps giving an error when opening it. For testing purposes i use ionic serve and check it in localhost.
angular.module('starter', ['ionic','ionic.service.core', 'ui.router'])
.controller('AgeCtrl', function ($scope, $state, $http, $cordovaGeolocation) {
$scope.toggleItem = function (item) {
item.checked = !item.checked;
};
$scope.items = [
{ id: '0-12' },
{ id: '12-18' },
{ id: '18-30' },
{ id: '30-65' },
{ id: '65+' }
];
$scope.time = Date.now();
$scope.weather = $http.get("http://api.openweathermap.org/data/2.5/weather?q=Amsterdam&units=metric&APPID=...").then(function(resp) {
console.log("success", resp);
}, function(err) {
console.log("error");
})
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
var lat = position.coords.latitude
var long = position.coords.longitude
console.log(lat + ' ' + long)
}, function(err) {
console.log(err)
});
$scope.Confirm = function (){
$state.go('home');
}
})
Is there any place i have made a mistake which causes this problem?
Ionic serve only emulates the application in the browser.
You do not get access to the Cordova plugins within the browser.
To get the libraries included you need to run the app on the device after adding a specific platform depending on what device you have.
For iOS:
Ionic platform add ios
For android:
ionic platform add android
After the platforms are added you can build and run on device using the following command
For iOS:
ionic run iOS
For android:
ionic run android
I believe the issue is with your ngCordova installation .
do below steps -
1- install --------------> bower install ngCordova
2- include in index.html above cordova.js ------------------> script src="lib/ngCordova/dist/ng-cordova.js"
3- inject -------------> angular.module(starter, ['ngCordova'])
run IONIC serve and issue will be gone .. If it still shows error that /dist/ngCordova is not present then go to location manually where ng cordova is installed and copy it to the path e.g. - /lib/ngCordova/dist/...
it will definitely resolve your issue
I think it's not referenced as $cordovaGeolocation in ionic. Try navigator.geolocation.getCurrentPosition instead?

GCM Android notification received on device but not displaying

GCM Cloud messaging notifications for my Ionic Android app are not appearing in my device's home screen, despite the notification registering in the app itself.
I'm using the npm module node-gcm to send push notifications.
var gcm = require('node-gcm');
var message = new gcm.Message({
priority: 'high',
contentAvailable: true,
delayWhileIdle: true,
timeToLive: 10,
dryRun: false,
data: {
key1: 'message1',
key2: 'message2'
},
notification: {
title: "Hello, World",
body: "This is a notification that will be displayed ASAP."
}
});
var regIds = ['*device id*'];
var sender = new gcm.Sender('*api key*');
sender.send(message, { registrationIds: regIds }, function (err, result) {
if(err) console.error(err);
else console.log(result);
});
When I send a push notification to my device's ID, I get a successful response:
{ multicast_id: 8406385547051869000,
success: 1,
failure: 0,
canonical_ids: 0,
results: [ { message_id: '0:1441962697347777%b67ee170f9fd7ecd' } ] }
I then get the following message in my Android Studio console:
V/GCMBroadcastReceiver﹕ onReceive: com.google.android.c2dm.intent.RECEIVE
V/GCMBroadcastReceiver﹕ GCM IntentService class: com.plugin.gcm.GCMIntentService
V/GCMBaseIntentService﹕ Acquiring wakelock
V/GCMBaseIntentService﹕ Intent service name: GCMIntentService-GCMIntentService-5
D/GCMIntentService﹕ onMessage - context: android.app.Application#2dc6dbff
V/GCMBaseIntentService﹕ Releasing wakelock
In the Google Play Developer Console GCM Debugger, my notifications also to appear to have been confirmed.
0: 1441899623073525% b67ee170f9fd7ecd Confirmed
Other than this I receive no error message in the Android Studio console when a notification has been received.
The Ionic app itself registers the notification once I've sent one. However when I'm out of the app. no notification is displayed in the home screen.
$rootScope.$on('$cordovaPush:notificationReceived', function (event, notification) {
alert(notification);
if (ionic.Platform.isAndroid() && notification.event == "registered") {
window.localStorage['token'] = notification.regid;
var params = {
deviceType: 'android',
tokenId: notification.regid
};
NotificationService.registerDevice(params);
}
if (notification.badge) {
$cordovaPush.setBadgeNumber(notification.badge);
}
//notifications payload
if (notification.foreground == '0') {
if (notification.view) {
$timeout(function () {
$state.go('app.notifications');
});
} else {
if (notification.id) {
NotificationService.markNotificationAsRead(notification.id).success(function () {
$rootScope.$emit('notifications-read');
});
}
if (notification.chat) {
$timeout(function () {
$state.go('app.message', {id: notification.chat});
});
} else if (notification.post) {
$timeout(function () {
$state.go('app.singlePost', {id: notification.post});
});
} else if (notification.group) {
$timeout(function () {
$state.go('app.group', {id: notification.group});
});
}
}
}
});
You must add icon field in your notification block:
notification: {
title: "Hello, World",
body: "This is a notification that will be displayed ASAP.",
icon: "#drawable/ic_launcher"
}
I was having the same issue, using the sample provided at the node-gcm page. After struggling for quite some time i came across this blogpost: http://devgirl.org/2012/10/25/tutorial-android-push-notifications-with-phonegap/
and modified my code according to the example provided in the blog post.
i guess there is an issue with "notification" object on node-gcm code, using message.addData seems to make it work,
in short replacing the message creation and sending logic as below worked for my application :
// For Android
if (row.device === "Android" && row.deviceToken) {
console.log(row.deviceToken);
var sender = new gcm.Sender(serverApiKey);
var message = new gcm.Message();
message.addData('title','İş Geliştirme Platformu');
message.addData('message','Yeni İleti');
message.addData('msgcnt','1');
//message.collapseKey = 'demo';
message.delayWhileIdle = true;
message.timeToLive = 3;
var registrationIds = [];
registrationIds.push(row.deviceToken);
sender.send(message, registrationIds, 4, function (err, result) {
console.log(result);
res.send(200,result);
});
}
add your server IP to white list and try again:
console.developers.google.com > APIs & auth > credential > select your server key > and add your server IP

Categories

Resources