7

用于检查当前网络连接的标准 PhoneGap API(见下文)似乎没有更新它在 Ripple Emulator 中的结果。当我更改连接类型并执行 checkConnection() 时,它会从第一次调用此函数时返回连接类型(在 deviceready 时)

function checkConnection() {    // Checks current network status
    networkState = navigator.connection.type;
    console.log(networkState);

    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';

    // DEBUG: notify on network state
    console.log("Connection type: " + states[networkState]);
}

我还需要做些什么(添加事件侦听器?)才能让它工作吗?通常,设备只会在状态从在线变为离线时触发事件,但我需要区分“免费”互联网和 xG 连接。

4

2 回答 2

8

显然 navigator.connection.type 在 windows 平台上的 cordova 中没有更新。查看代码,navigator.connection.type 仅在 'deviceready' 事件之后设置一次。

诀窍是在相关事件上使用 Connection#getInfo() 手动更新它

var connection = navigator.connection;
function errorCallback(e) {
  console.warn(e);
};
function updateConnection(info) {
  connection.type = info;
}
document.addEventListener("resume", function() {
  connection.getInfo(updateConnection, errorCallback);
});
document.addEventListener("online", function() {
  connection.getInfo(updateConnection, errorCallback);
});
document.addEventListener("offline", function() {
  connection.getInfo(updateConnection, errorCallback);
});

免责声明:从我自己的代码中重构/复制粘贴的部分,应该可以开箱即用。

于 2015-01-06T08:32:40.633 回答
-1

我会说尝试添加一个超时功能来延迟通话。当这解决了问题时,我已经看到了类似的问题。首先执行以下操作:

networkState = navigator.connection.type;

然后:

setTimeout(function(){

    networkState = navigator.connection.type; // have to do this second time to pick up the refreshed value
    console.log(networkState);

    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';

    // DEBUG: notify on network state
    console.log("Connection type: " + states[networkState]);
}, 500);

这给了 navigator.connection.type 时间(本例中为 500 毫秒)来刷新它的值。

于 2013-10-24T16:28:34.913 回答