I am working on Ionic Framework, and facing issues using the Apache Cordova Network API to detect internet connection in Android App. I have referred this tutorial and also created a demo project, which works fine.
I have followed the below steps. [from the tutorial]
ionic start testApp sidemenu
ionic platform add android
Open testApp/www/js/app.js
Copy paste this code
if(window.Connection) {
if(navigator.connection.type == Connection.NONE) {
alert('There is no internet connection available');
}else{
alert(navigator.connection.type);
}
}else{
alert('Cannot find Window.Connection');
}
Install Cordova Plugin cordova plugin add org.apache.cordova.network-information
Build ionic build android
Run ionic run android
This works fine
Issue
www
from mainproject
to testApp
and do steps 6 and 7I get a alert Cannot find Window.Connection
After copy pasting the app.js
looks like this
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
// check internet connection
//alert(window.Connection);
alert('Hi')
try {
alert('Naviagtor says'+navigator.connection.type);
}
catch(err) {
alert( 'Error '+ err.message)
//here i get 'Error cannot read property type of undefined'
}
if(window.Connection) {
if(navigator.connection.type == Connection.NONE) {
alert('There is no internet connection available');
}else{
alert(navigator.connection.type);
}
}else{
alert('Cannot find Window.Connection');
}
});
})
The moment I copy paste my app.js
and controllers.js
to the testApp/www/js
directory the whole thing blows up.
Any help in debugging is highly appreciated.
Thanks,
Note
I do have cordova.js
in index.html
.
I have re installed platforms
and plugins
after copy paste as well.
I solved a similar issue by using ngcordova . It gives you an angular wrapper around the plugin that implements promises.
Often Cordova plugins aren't ready when you try to call them, using the promise interface you can avoid getting undefined errors.
I stole the example from the ngcordova page on the network plugin here.
module.controller('MyCtrl', function($scope, $rootScope, $cordovaNetwork) {
document.addEventListener("deviceready", function () {
var type = $cordovaNetwork.getNetwork()
var isOnline = $cordovaNetwork.isOnline()
var isOffline = $cordovaNetwork.isOffline()
// listen for Online event
$rootScope.$on('networkOffline', function(event, networkState){
var onlineState = networkState;
})
// listen for Offline event
$rootScope.$on('networkOffline', function(event, networkState){
var offlineState = networkState;
})
}, false);
});