Device Orientation and Cordova - angularjs

I have a problem with Device Orientation, Ionic and Cordova/ngCordova
I've already run the command:
"cordova plugin add cordova-plugin-device-orientation"
to install the device orientation plugin
It installed without problem.
Then I add the following code to my app:
.controller('MyCtrl', function ($scope,$cordovaDeviceOrientation) {
$cordovaDeviceOrientation.getCurrentHeading().then(function(result) {
var magneticHeading = result.magneticHeading;
var trueHeading = result.trueHeading;
var accuracy = result.headingAccuracy;
var timeStamp = result.timestamp;
$scope.values=magneticHeading+" "+trueHeading+" "+accuracy+" "+timeStamp;
}, function(err) {
// An error occurred
});
})
After executing cordova run android I got this error.
Cannot read property 'getCurrentHeading' of undefined.
I tested this code on the browser, Genymotion or Samsung Galaxy Tab 4, but always I got the same error.
What am I doing wrong?

There's two things you need to know:
First: This kind of plugin, like device orientation, need to be tested in real devices once it use a accelerometer hardware to work.
Second: You need to use the DeviceReady EventListner to use the plugins, so, you need to do something like this:
document.addEventListener("deviceready", function () {
$cordovaDeviceOrientation.getCurrentHeading().then(function(result) {
var magneticHeading = result.magneticHeading;
var trueHeading = result.trueHeading;
var accuracy = result.headingAccuracy;
var timeStamp = result.timestamp;
$scope.values=magneticHeading+" "+trueHeading+" "+accuracy+" "+timeStamp;
}, function(err) {
// An error occurred
});
}, false);
If you want, there's a seed for angularjs + cordova + angular-material here:
https://github.com/marioaleogolsat/cordova-angular-angularMaterial-seed

Your device may not have a compass.

Related

Node JS - Use Printer (Hardware)

I'm developing an application with Angular JS and Node JS where I need to see all available printers in the user's machine, let the user select one of them and print a receipt.
Is there a way to achieve this?
I did an application like that.. I did it using http://nwjs.io/ and the module in the comment: https://www.npmjs.com/package/printer, here is a working code with this module printing raw in the default printer a file:
var printer = require('printer');
var fs = require('fs');
var info = fs.readFileSync('ticket.txt').toString();
function sendPrint() {
printer.printDirect({
data: info,
type: 'RAW',
success: function (jobID) {
console.log("ID: " + jobID);
},
error: function (err) {
console.log('printer module error: '+err);
throw err;
}
});
}
sendPrint();
you can adapt it to use the getPrinters() method to enumerate all installed printers and then allow the user to select the desired one.

cordovaGeolocation error: position retrieval timed out

Hello I want to implement some geolocation features in my app.
So I implemented a watchposition function like this:
.controller('NavigationCtrl', function ($scope,$cordovaGeolocation) {
var watchOptions = {
frequency : 1000,
timeout : 20*1000,
enableHighAccuracy: false // may cause errors if true
};
var watch = $cordovaGeolocation.watchPosition(watchOptions);
watch.then(
null,
function(err) {
alert("WatchPosition failed: "+JSON.stringify(err));
},
function(position) {
$scope.position = position;
}
);
})
Well in the first call of the template I get a geolocation but than after 20 seconds I get an error:
code:3, message:'Position retrieval timed out'
I'm testing the app on a iPhone 5s iOS 8.3.
I googled around and found out that cordova 3.1 has some errors with geolocations so I choose to use the html api for geolocations like here:
https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation
but it didn't show me anything in my ionic-framework app.
What am I missing?
I'm using cordova 4.3.0 and ionic 1.3.19.
I found out that I have to put the code in a $ionicPlatform.ready function to be sure that the device is ready before it start geolocating. Now it working fine.

Connection state with doowb/angular-pusher

I am trying to build an Angular project with Pusher using the angular-pusher wrapper. It's working well but I need to detect when the user loses internet briefly so that they can retrieve missed changes to data from my server.
It looks like the way to handle this is to reload the data on Pusher.connection.state('connected'...) but this does not seem to work with angular-pusher - I am receiving "Pusher.connection" is undefined.
Here is my code:
angular.module('respondersapp', ['doowb.angular-pusher']).
config(['PusherServiceProvider',
function(PusherServiceProvider) {
PusherServiceProvider
.setToken('Foooooooo')
.setOptions({});
}
]);
var ResponderController = function($scope, $http, Pusher) {
$scope.responders = [];
Pusher.subscribe('responders', 'status', function (item) {
// an item was updated. find it in our list and update it.
var found = false;
for (var i = 0; i < $scope.responders.length; i++) {
if ($scope.responders[i].id === item.id) {
found = true;
$scope.responders[i] = item;
break;
}
}
if (!found) {
$scope.responders.push(item);
}
});
Pusher.subscribe('responders', 'unavail', function(item) {
$scope.responders.splice($scope.responders.indexOf(item), 1);
});
var retrieveResponders = function () {
// get a list of responders from the api located at '/api/responders'
console.log('getting responders');
$http.get('/app/dashboard/avail-responders')
.success(function (responders) {
$scope.responders = responders;
});
};
$scope.updateItem = function (item) {
console.log('updating item');
$http.post('/api/responders', item);
};
// load the responders
retrieveResponders();
};
Under this setup how would I go about monitoring connection state? I'm basically trying to replicate the Firebase "catch up" functionality for spotty connections, Firebase was not working overall for me, too confusing trying to manage multiple data sets (not looking to replace back-end at all).
Thanks!
It looks like the Pusher dependency only exposes subscribe and unsubscribe. See:
https://github.com/doowb/angular-pusher/blob/gh-pages/angular-pusher.js#L86
However, if you access the PusherService you get access to the Pusher instance (the one provided by the Pusher JS library) using PusherService.then. See:
https://github.com/doowb/angular-pusher/blob/gh-pages/angular-pusher.js#L91
I'm not sure why the PusherService provides a level of abstraction and why it doesn't just return the pusher instance. It's probably so that it can add some of the Angular specific functionality ($rootScope.$broadcast and $rootScope.$digest).
Maybe you can set the PusherService as a dependency and access the pusher instance using the following?
PusherService.then(function (pusher) {
var state = pusher.connection.state;
});
To clarify #leggetters answer, you might do something like:
app.controller("MyController", function(PusherService) {
PusherService.then(function(pusher) {
pusher.connection.bind("state_change", function(states) {
console.log("Pusher's state changed from %o to %o", states.previous, states.current);
});
});
});
Also note that pusher-js (which angular-pusher uses) has activityTimeout and pongTimeout configuration to tweak the connection state detection.
From my limited experiments, connection states can't be relied on. With the default values, you can go offline for many seconds and then back online without them being any the wiser.
Even if you lower the configuration values, someone could probably drop offline for just a millisecond and miss a message if they're unlucky.

Sencha + Windows phone 8 : Launch function is not invoked

I have built a sencha application using Sencha cmd.
I have integrated it to windows phone using cordova.
Now, when launching the app, after splash screen, a white screen comes and stays for ever.
I trying putting an alert in the launch function (in app.js where view is created) and found out that the launch function does not fire.
What could be the reason of this behaviour?
I found the cause of the issue that I was facing. The sencha app is using a store with SQL proxy. But since SQL proxy is not supported on Windows phone (but supported on other platforms viz. iOS, Android), so the launch function was not getting called.
I had a similar problem with a JSON proxy and I had to modify the following lines of code in cordovalib/XHRHelper.cs file.
var funk = function () {
window.__onXHRLocalCallback = function (responseCode, responseText) {
alias.status = responseCode;
if (responseCode == '200') {
alias.responseText = responseText;
try {
JSON.parse(responseText);
} catch (e) {
Object.defineProperty(alias, 'responseXML', {
get: function () {
return new DOMParser().parseFromString(this.responseText, 'text/xml');
}
});
}
Object.defineProperty(alias, 'responseJSON', {
get: function () {
return new DOMParser().parseFromString(this.responseText, 'text/json');
}
});
}else {
alias.onerror && alias.onerror(responseCode);
}

How to alert the user when there's no internet connection

I need to alert the user with the following conditions;
Request timed out
No internet connection
Unable to reach the server
Here's the code; How to capture the following conditions when occurred and alert the user ?
failure: function (response) {
var text = response.responseText;
console.log("FAILED");
},success: function (response) {
var text = response.responseText;
console.log("SUCCESS");
}
I tried the following code to check if the internet is reachable, but it didn't work
var networkState = navigator.network.connection.type
alert(states[networkState]);
if (networkState == Connection.NONE){
alert('No internet ');
};
UPDATE **
I added the following in my index.html, but, when i disable WIFI, i don't see the alert popping.
<script>
function onDeviceReady() {
document.addEventListener("offline", function() {
alert("No internet connection");
}, false);
}
</script>
The best thing to do is to listen to the "offline" event. When you get the offline event you can warn your user and take whatever steps necessary to save data, etc.
For instance, your "deviceready" callback:
document.addEventListener("offline", function() {
alert("No internet connection");
}, false);
This code should work for most all versions of PhoneGap. It's been in since at least the 1.0 release.
Exactly as Simon said, you can use
document.addEventListener("offline", youCallbackFn, false);
or you can interrogate the boolean property
navigator.onLine
(Should return true or false)
However, this technique will tell you whether device is connected. The caveat is such that device can be connected to WiFi, but the router might be offline. In that case, use a polling mechanism, like timely Ext.Ajax.request with lower timeouts. Timeout expired = offline.
You can use PhoneGap's NETWORK API
The network object gives access to the device's cellular and wifi connection information.
You can test it in the following way,
function onDeviceReady() {
navigator.network.isReachable("phonegap.com", reachableCallback, {});
}
// Check network status
//
function reachableCallback(reachability) {
// There is no consistency on the format of reachability
var networkState = reachability.code || reachability;
var states = {};
states[NetworkStatus.NOT_REACHABLE] = 'No network connection';
states[NetworkStatus.REACHABLE_VIA_CARRIER_DATA_NETWORK] = 'Carrier data connection';
states[NetworkStatus.REACHABLE_VIA_WIFI_NETWORK] = 'WiFi connection';
alert('Connection type: ' + states[networkState]);
}
You can add 'Ext.device.Connection' in app.js of your application. And check your device is online or offline using code:
if (Ext.device.Connection.isOnline()) {
alert('Connected to internet');
}
else{
alert('You are not connected to internet');
}
Just Embed this in your tag
<body onoffline="alert('PLEASE CHECK YOUR INTERNET SETTING');">

Resources