Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if phone is online/offline with PHONEGAP reachability API

Tags:

iphone

cordova

Hi and thanks in advance,

I'm aware Phonegap has a reachability API and I'd like to know how I can use it to detect if the phone is connected to the network or not.

What I found is here: http://github.com/phonegap/mobile-spec/blob/master/tests/network.tests.js

I just don't know how to use it or if it even suits my needs.

Thanks again.

like image 667
StJimmy Avatar asked Nov 27 '25 16:11

StJimmy


2 Answers

With the newest update, the method for checking if the device is online has changed - check out the API documentation at http://docs.phonegap.com/phonegap_connection_connection.md.html#Connection.

Here is the code that they use as an example:

<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
<script type="text/javascript" charset="utf-8">

// Wait for PhoneGap to load
// 
document.addEventListener("deviceready", onDeviceReady, false);

// PhoneGap is loaded and it is now safe to make calls PhoneGap methods
//
function onDeviceReady() {
    checkConnection();
}

function checkConnection() {
    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]);
}

</script>
like image 181
Zorayr Avatar answered Nov 29 '25 06:11

Zorayr


http://docs.phonegap.com/en/2.1.0/cordova_connection_connection.md.html#Connection

I noticed you had a few questions regarding phoneGap, there is alot of information in there documentation that I have linked to above... enjoy

like image 24
Aaron Saunders Avatar answered Nov 29 '25 06:11

Aaron Saunders



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!