如何检查移动互联网连接

How to check mobile internet connection

本文关键字:移动互联网 连接 检查 何检查      更新时间:2023-09-26

我必须根据互联网/连接可用性调用两个函数。

如果存在互联网连接,则调用插入函数,否则调用更新。

我试过这样:

var online = window.navigator.onLine;
    if (online==ture) {
        alert('connection down.');
    }else
    {
      alert('Please check your internet connection and try again');
    }

此代码仅适用于浏览器,不适用于设备。在这两种情况下,它总是显示alert('connection down');,即是否存在互联网。

请指导此代码,因为我是Phonegap的新手。

使用此插件满足您的需求(https://github.com/apache/cordova-plugin-network-information)。安装后,请尝试使用此代码以检查互联网连接。

document.addEventListener("deviceready",checkInternet,false);
function checkInternet(){
   if(navigator.connection.type=="none"){
     //no internet connection
     alert("No connection");    
    }else{
     alert("Connection ok");
    }
}
它是

HTML5 API的一部分。检查 window.navigator.onLine 的值 -- 如果用户处于脱机状态,则为 false。当浏览器联机和脱机时,指示器会更新。

   <head>
   <title>Online status</title>
   <script>
   function updateIndicator() 
   {
     document.getElementById('indicator').textContent = navigator.onLine ? 'online' : 'offline';
   }
   </script>
   </head>
   <body onload="updateIndicator()" ononline="updateIndicator()" onoffline="updateIndicator()">
   <p>The network is: <span id="indicator">(state unknown)</span>
  </body>

欲了解更多信息

您使用的 API 在移动设备上不起作用。您需要改用网络 API。

您需要做:

  1. 通过CL使用以下命令添加网络插件

    cordova plugin add org.apache.cordova.network-information

  2. 现在获取网络状态为

    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.CELL]     = 'Cell generic connection';
        states[Connection.NONE]     = 'No network connection';
        alert('Connection type: ' + states[networkState]);
    }
    checkConnection();