Frage

Hello to all guys I have a BIG problem with my Android App. I need to run some Ajax call but for first I wanna check the connection status. So I installed the plugin on my cordova project (cordova is 3.4.1 I think) and then I add this function on my JS and I call it before ajax call:

function checkConnection() {

    if(navigator.network.connection.type == Connection.NONE || navigator.network.connection.type ==Connection.UNKNOWN){
       return false;
    }else{
       return true;
    }
}

But there is a problem: IF I'm connected the function return TRUE but if I disable the WIFI (I only have an Nexus 7 2013 ONLY WIFI) and I call it, the app thrown an alert with "error" string :( how can I fix it?

War es hilfreich?

Lösung

This is because if you turn WIFI off the type porperty of navigator.network.connection will not get initialised.

I would implement an extra check:

if (typeof navigator.connection !== "undefined") 

Something like:

function checkConnection() {

    if (typeof navigator.connection !== "undefined") {

        if(navigator.network.connection.type == Connection.NONE || navigator.network.connection.type ==Connection.UNKNOWN){
            return false;
        }else{
            return true;
        }

    } else {
        return false;
    }
}     

Andere Tipps

Since it is a mobile app, this is how i defined it in my project,

function hasNetworkConnectivity() {
    try{
        if(navigator.network.connection.type == Connection.UNKNOWN){
            return false;
        }else if(navigator.network.connection.type == Connection.ETHERNET){
            return true;
        }else if(navigator.network.connection.type == Connection.WIFI){
            return true;
        }else if(navigator.network.connection.type == Connection.CELL_2G){
            return true;
        }else if(navigator.network.connection.type == Connection.CELL_3G){
            return true;
        }else if(navigator.network.connection.type == Connection.CELL_4G){
            return true;
        }else{
            return false;
        }
    }catch(e){
        return true;
    }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top