用于检查当前网络连接的标准PhoneGap API(见下文)似乎没有在Ripple Emulator中更新它的结果.当我更改连接类型并执行checkConnection()时,它会从第一次调用此函数返回连接类型(在deviceready处) f
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连接.
查看代码,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); });
免责声明:我自己的代码中的重构/复制粘贴片段应该开箱即用.