PhoneGap检测设备网络连接情况

一、网络连接状态列表

  Phonegap 网络连接通过 navigator.network.connection.type 来获取,一般有一下几种状态

    1. Connection.UNKNOWN               未知连接

    2. Connection.ETHERNET               以太网

    3. Connection.WIFI                      WiFi

    4. Connection.CELL_2G                  2G 网络

    5. Connection.CELL_3G                       3G 网络

    6. Connection.CELL_4G                           4G 网络

    7. Connection.NONE                          无网络连接

 

 

 

二、代码实现

<!DOCTYPE html> 

<html>

<head>

<meta charset="utf-8">

<title>phonegap_device_network_notification01</title>

<link href="../jquery.mobile-1.3.2.css" rel="stylesheet" type="text/css"/>

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

<script src="../jquery.mobile-1.3.2.js" type="text/javascript"></script>

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

<script type="text/javascript" charset="utf-8">

    document.addEventListener("deviceready", onDeviceReady, false);

    function onDeviceReady() {

        // 监听网络的变化

        //window.addEventListener("online", onOnline, false);

        //window.addEventListener("offline", onOffline, false);

        //console.log('网络类型'+navigator.network.connection.type);

        alert('网络类型'+navigator.network.connection.type);//这样就可以检测出来是什么类型的网络连接        

        

        // 检查网络连接

        checkNetworkConnection();

    }

    function checkNetworkConnection() {

        var states = {};  //封装到数组中

        states[Connection.UNKNOWN]  = '未知连接';

        states[Connection.ETHERNET] = '以太网';

        states[Connection.WIFI]     = 'WiFi';

        states[Connection.CELL_2G]  = '2G网络';

        states[Connection.CELL_3G]  = '3G网络';

        states[Connection.CELL_4G]  = '4G网络';

        states[Connection.NONE]     = '无网络连接';

        alert('网络连接类型: ' + states[navigator.network.connection.type]);

    }

    function onOnline() {

        alert('您现在在线');

    }

    function onOffline() {

        alert('您现在离线');

    }

</script>

</head> 

<body>

<div data-role="page">

        <div data-role="header">

            <h1>PhoneGap100实战</h1>

        </div>

        <div data-role="content">

            <input type="button" value="检查网络" onClick="checkNetworkConnection()" />

        </div>

        <div data-role="footer">

            <h4>&nbsp;</h4>

        </div>

</div>



</body>

</html>

 

你可能感兴趣的:(PhoneGap)