Question

Please help. I have the below function which is run infinitely:

    // Check the connection state of the device
    function checkConnection() {

        var networkState = "";
        networkState = navigator.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.CELL]     = 'Cell generic connection';
        states[Connection.NONE]     = 'No network connection';

        if (states[networkState] === 'No network connection') {
            noNetworkAlertCreate();
        } else {
            noNetworkAlertRemove();
        }

        checkConnection();
    }

As soon as the device is ready this function is called:

    // Device is ready let's do this
    function onDeviceReady() {
        checkConnection();
    }

The function is correctly looped but the connection state is somehow not updated with every loop. If the state was first registered as WIFI it is not updated when run again and registers as WIFI again even though WIFI has been disabled.

Any advice?

Much appreciated

Was it helpful?

Solution

ondeviceready will only fire once when cordova is fully loaded. You will want to call the same function when different events occur like 'online' and 'offline'.:

// Device is ready let's do this
function onDeviceReady() {
    checkConnection();
}

document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener("online", checkConnection, false);
document.addEventListener("offline", checkConnection, false);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top