检查Phonegap上的网络连接

时间:2016-02-09 23:53:11

标签: javascript cordova phonegap-plugins

我是一个Javascript新手和一个PhoneGap新手...

我知道这个问题已经以多种方式发布,但我无法在此处获得基础知识。我试图复制其他答案,但我似乎无法使用网络信息插件: https://github.com/apache/cordova-plugin-network-information

此时我真的只想要一个在启动时检查网络连接的准系统示例(onDeviceReady),然后再检查用户的设备是否已从在线更改为脱机和副本反之亦然(见过一些人建议这件作品的setTimeout)。

经过一些测试后,似乎我的navigator.connection.type检查没有触发。

我安装了org.apache.cordova.network-inforamtion。请帮忙......我花了大约一个星期把头发拉出来。 :)

我的代码:

<script type="text/javascript" src="js/ga.js">

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

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

        function checkConnection() {
            var 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.NONE]     = 'No network connection';

            alert('Connection type: ' + states[networkState]);
        }

        document.addEventListener("offline", onOffline, false);

        function onOffline() {
            // Handle the offline event
            alert('Offline');
        }

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

        function onOnline() {
            // Handle the online event
            alert('Online');
        }


    </script>

1 个答案:

答案 0 :(得分:1)

Install network plugin org.apache.cordova.network-information and try the following:-

document.addEventListener("resume", getintoForeground, false);  

function getintoForeground(){
var ntwk = CheckConnection();

if (ntwk) {
    alert("Network available");
}else{
    alert("Network  not available");
}
}

function CheckConnection(){
    if( !navigator.network ){
                navigator.network = window.top.navigator.network;
    }
    return ( (navigator.network.connection.type === "none" || navigator.network.connection.type === null || 
                navigator.network.connection.type === "unknown" ) ? false : true );
    }