问题
I am new to Phonegap and JqueryMobile. I need to check the internet connection on device. After seeing some solution on net I got confused about approaches. some solutions is suggesting to use PG API like network manager and connection while some using JQMobile method to check connection.
My question is which to prefer ? or what are the target areas for both the implementation ?
回答1:
PhoneGap have own function to check Internet connection available or not.Here is that official document.
- Check Internet is Online
document.addEventListener("online", onOnline, false); - Check Internet is Offline
document.addEventListener("offline", onOffline, false);
You need to set
<plugin name="NetworkStatus" value="org.apache.cordova.NetworkManager" /> permission in config.xml for android.
You have to add some permission in manifest as below,
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"> </uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"> </uses-permission>
<uses-permission android:name="android.permission.INTERNET" />
回答2:
Try this
Working example: http://jsfiddle.net/Gajotres/d5XYR/
In this case timer will check internet connection every 100 ms and set final result into a javascript global variable.
Everything depends on this line:
window.navigator.onLine -- it will be false if the user is offline.
Final solution:
var connectionStatus = false;
$(document).on('pagebeforeshow', '#index', function () {
setInterval(function () {
connectionStatus = navigator.onLine ? 'online' : 'offline';
}, 100);
$(document).on('click', '#check-connection', function () {
alert(connectionStatus);
});
});
来源:https://stackoverflow.com/questions/20782860/phonegap-check-internet-connection-on-device-vs-mobile-browser