How to check device is Online or Offline Phonegap

蹲街弑〆低调 提交于 2019-12-04 20:45:25

问题


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();

回答1:


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




回答2:


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;
    }
}



回答3:


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");
        }
    }
});



回答4:


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.




回答5:


the native onLine is somewhat shaky, especially in an web app environment.. but can be used for an initial check upon pageLoad, however it is somewhat useless then as if you get to that point you have an internet connection.

attempting to ajax something is far more reliable.



来源:https://stackoverflow.com/questions/17833542/how-to-check-device-is-online-or-offline-phonegap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!