I'm doing an non-native app in Phonegap and I want to know when I have connection or not. Searching on the WEB, I found a way of how to know if I get a connection in my app, but I implemented in my code and doesn't worked.
The way I found was this:
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is loaded and it is now safe to make calls PhoneGap methods
function onDeviceReady() {
check_my_Connection();
}
function check_my_Connection() {
var networkState = navigator.network.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.NONE] = 'No network connection';
alert('Connection type: ' + states[networkState]);
}
And I call the function onDeviceReady()
in the ready
function of my script like this:
<script type="text/javascript">
$(document).ready(function(){
/*other code*/
onDeviceReady();
/*other chode*/
});
/*other code functions*/
/*Before the rest of the code, I added the snippet code above of this*/
document.addEventListener("deviceready", onDeviceReady, false);
...
</script>
I read that I need a cordova.js
, but the PhoneGap Desktop App (beta version) doesn't created it. This JS file is required to do this work? Exist another way to detect the connection in the Phonegap apps, without using jQueryUI or jQueryMobile? I need to do some change (s) in some file (s) of my project?
I'll appreciate any help or any way to do this.
P. S.: excuse me for my english.
The problem has to be inside your code. Just do the following to receive the connection state:
cordova create networkInformation com.example.com networkInformation
cd networkInformation
cordova platform add android
cordova plugin add cordova-plugin-network-information
cordova build
After you finished this process, you open up the created folder on your desktop. Move inside the
www
folder inside theplatform
->android
folder underassets
. Open your index.js which should look like this:So now look for
And change it to this:
Also add
directly above
app.initialize();
This should be your full index.js then. Just launch your application and it'll alert you your network state: