设备未检测到在线/离线状态

时间:2014-06-19 09:06:33

标签: javascript android jquery jquery-mobile cordova

在我的phonegap应用程序中,我想检查设备的在线/离线状态。

Cordova version is 3.3
Android version 4.2.2
Jquery Mobile 1.3

所以我使用以下方法来检测在线/离线。 方法1:

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

function onDeviceReady(){   
    connectionStatusOnline = navigator.onLine ? 'online' : 'offline';
    alert(connectionStatusOnline);
}

它始终返回离线

方法2:

document.addEventListener("online", toggleon, false);
    document.addEventListener("offline", toggleoff, false);
function toggleon() {
    alert("online");

}
function toggleoff() {
    alert("offline");

}

方法2中,它从不调用toogleon或toogleoff

方法3:

function onDeviceReady() {
//document.addEventListener("offline", toggleCon, false);
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]);
}
方法3中的

显示未定义连接

我拥有config.xml and set all the permission in manifest中的所有插件。

2 个答案:

答案 0 :(得分:2)

您的cordova.js和cordova_plugin.js文件似乎位于www / js文件夹中。So the file API's are called in this staratergy。因此设备未检测到设备处于离线/在线状态。我之前遇到过类似的问题。我做了什么把cordova.js和cordova_pluins.js文件复制到 www 文件夹

您的project directory should be like www/cordova.js and www/cordova_plugins.js

不是www/js/cordova.js and www/js/cordova_plugin.js

答案 1 :(得分:0)

通过CLI添加网络插件... Link

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

然后

<script>

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

    function onDeviceReady()
    {

        if(navigator.connection.type==0)
        {
              toggleoff();  
        }
        else if(navigator.connection.type=='none')
        {
              toggleoff();  
        }
        else
        {
              toggleon();
        }

     }
</script>