plug phonegap-plugin-push to Firebase - javascript

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.

Related

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

Phonegap Plugin Push & Node-gcm NotRegistered

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!

Handle Push notification in Nativescript

I am working on application in Nativescript which implements push notification. Lets say server sends push notification and based on action mentioned in payload of notification i will have to redirect in application. This redirection should be performed if user taps on notification from drawer and application is in background. Other case when application should not redirect if its in foreground. I have managed a flag for that as follow
app.js
application.on(application.launchEvent, function (args) {
appSettings.setBoolean('AppForground', true);
});
application.on(application.suspendEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
application.on(application.resumeEvent, function (args) {
appSettings.setBoolean('AppForground', true);
});
application.on(application.exitEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
application.on(application.lowMemoryEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
application.on(application.uncaughtErrorEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
And on Push notification listener
var settings = {
// Android settings
senderID: '1234567890', // Android: Required setting with the sender/project number
notificationCallbackAndroid: function(data, pushNotificationObject) { // Android: Callback to invoke when a new push is received.
var payload = JSON.parse(JSON.parse(pushNotificationObject).data);
if (appSettings.getBoolean('AppForground') == false){
switch (payload.action) {
case "APPOINTMENT_DETAIL":
frame.topmost().navigate({
moduleName: views.appointmentDetails,
context: {
id: payload.id
}
});
break;
case "MESSAGE":
frame.topmost().navigate({
moduleName: views.appointmentDetails,
context: {
id: payload.id,
from: "messages"
}
});
break;
case "REFERENCES":
frame.topmost().navigate({
moduleName: views.clientDetails,
context: {
id: payload.id,
name: ""
}
});
break;
default:
}
}
},
// iOS settings
badge: true, // Enable setting badge through Push Notification
sound: true, // Enable playing a sound
alert: true, // Enable creating a alert
// Callback to invoke, when a push is received on iOS
notificationCallbackIOS: function(message) {
alert(JSON.stringify(message));
}
};
pushPlugin.register(settings,
// Success callback
function(token) {
// if we're on android device we have the onMessageReceived function to subscribe
// for push notifications
if(pushPlugin.onMessageReceived) {
pushPlugin.onMessageReceived(settings.notificationCallbackAndroid);
}
},
// Error Callback
function(error) {
alert(error);
}
);
Now the problem, is that if application is in killed state and notification arrives. Then it sets flag to true as application is launched which it should not. So due to that redirection is not performed and in other cases when application is in foreground state then also its navigating through pages (which should not be) on receiving notification.
I doubt about flag management is causing the problem but not sure. Would you please guide me if anything is wrong with what i did ?
UPDATE
I am using push-plugin.
Thanks.
I use this for notifications
https://github.com/EddyVerbruggen/nativescript-plugin-firebase
This plugin use FCM, it adds to datas received from notifications foreground parameter so from payload you can determine if app was background(foreground==false, app is not active or was started after notification arrived) or foreground(foreground==true, app is open and active), but you need to some changes to code as they are different plugins
You can use pusher-nativescript npm module.
import { Pusher } from 'pusher-nativescript';
/*Observation using the above.
- Project gets build successfully.
- on run -> ERROR TypeError: pusher_nativescript__WEBPACK_IMPORTED_MODULE_6__.Pusher is not a constructor
- Use: import * as Pusher from 'pusher-nativescript';
- Make sure to install nativescript-websocket with this package.
*/
var pusher = new Pusher('Your_app_key', { cluster: 'your_cluster_name' });
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
alert(JSON.stringify(data));
});

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?

Categories

Resources