我看到几个不同的选项来检查与phonegap的互联网连接.有document.addEventListener(“online”,onOnline,false);还有navigator.network.connection.type ……但我不确定哪一个是最佳实践.我还希望能够防止手机连接到wifi网络但没有互联网连接的坏情况.
$(document).on('pagecreate','#explanation-short',function(){ if ( isPhoneGap() ) { if (checkConnection() == "none" ) { connectionStatus = 'offline'; } else { connectionStatus = 'online'; } function checkConnection() { var networkState = navigator.network.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.NONE] = 'No network connection'; //console.log('Connection : ' + Connection); //console.log('Connection type: ' + states[networkState]); return networkState; } } else { connectionStatus = navigator.onLine ? 'online' : 'offline'; } console.log("connectionStatus : "+connectionStatus); });
例如,如果手机连接到wifi,此代码有效,但我们不确定互联网是否实际可用.
phonegap 3.3和Jquery mobile 1.4的最佳实践是什么?
解决方法
事件,
document.addEventListener("online",false);
仅在您的应用已加载并重新获得连接时才会触发.在应用程序启动时不会触发此操作.
因此,您必须在启动应用程序时使用checkConnection()方法,然后如果您需要在应用程序运行时稍后检查,则使用事件侦听器.