用于检查当前网络连接的标准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连接。
答案 0 :(得分:7)
显然,navigator.connection.type并未在Windows平台上的cordova中进行更新。 看一下代码,navigator.connection.type只在' deviceready'之后设置一次。事件
Trick是在相关事件
上使用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);
});
免责声明:我自己的代码中的重构/复制粘贴片段应该是开箱即用的。
答案 1 :(得分:-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毫秒)以刷新它的值。