Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check device is Online or Offline Phonegap

What is the easiest way to check whether the device(smartphone) is online or offline. I'm working with phonegap, jquery mobile. I found this one.

document.addEventListener("online", yourCallbackFunction, false);

What I want to do is to check the Internet connection and decide about to get the data from the internet or from the device local database.

if(deviceoffline)
  getDataFromLokalDatabase();
else
  getDataFromInternet();
like image 913
Erdem Güngör Avatar asked Jul 24 '13 12:07

Erdem Güngör


4 Answers

This is the code using native phonegap code:

function checkInternet() {

    var networkState = navigator.connection.type;

    if(networkState == Connection.NONE) {

        onConnexionError();
        return false;

    } else {

       return true;
    }
}
like image 164
Someoneinthe Avatar answered Nov 20 '22 02:11

Someoneinthe


You can use navigator.onLine:

var isOffline = 'onLine' in navigator && !navigator.onLine;

if ( isOffline ) {
    //local db
}
else {
    // internet data
}

But be aware of that if navigator.onLine isn't supported isOffline will always be false

like image 37
Andreas Louv Avatar answered Nov 20 '22 04:11

Andreas Louv


Using Jquery make a ajax call and check the error code, If you get error code as 0 the device is offline

$.ajax({
    //your ajax options
    error: function (request) { 
         if (request.status == 0) {
            alert("you're offline");
        }
    }
});
like image 30
Divesh Salian Avatar answered Nov 20 '22 02:11

Divesh Salian


Beware, while navigator.onLine is the simplest solution, it does not behave consistently on all browsers. On Chrome it will tell you that it is online if you have a LAN cable in, even if you have no internet.

You can use the cordova plugin network-information

You can also try to make an AJAX request to your server; usually you want to know if you are offline because in that case you cannot communicate with the server, so "offline" often means "not able to communicate with the server" (which can be also caused by your server being offline). Playing with timeouts or several requests is also useful if you need to check bandwidth or link quality.

Offline does not mean the same for every use case, you first need to know which of the above techniques is best suited for you, then implement one or several of them.

What I want to do is to check the Internet connection and decide about to get the data from the internet or from the device local database.

It seems that checking the link with your server through a request is the best option for you.

like image 33
Rayjax Avatar answered Nov 20 '22 03:11

Rayjax