Tuesday, 1 November 2011

Network Reachability Code in Phonegap




// Wait for PhoneGap to load

// 
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
// PhoneGap is loaded and it is now safe to make calls PhoneGap methods
//
function onDeviceReady() {

}

function checkReachability() {
var _check=true;

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: '+ networkState + states[networkState]);
  if(networkState==="unknown"){
  _check=false;
  showAlert();
  return _check;
  }
  else {
  return true;
  }
  
}

function showAlert() {
navigator.notification.alert("Please connect your device to Internet.",onDeviceReady,"No Network Connectivity","OK");
}


Putting this code  in one js file i.e named as network_reachability.js


onload function calls on HTML page.
 <body onload="onload()">
Use checkReachability function where you check internet connectivity.


Enjoy :)

2 comments: