[英]Checking Network Connection on Phonegap
I'm a Javascript novice and a PhoneGap Newbie... 我是Javascript新手和PhoneGap新手...
I know this question has been posted in numerous ways, but I just can't get the basics to work here. 我知道这个问题已经以多种方式发布了,但是我只是无法获得在这里工作的基础知识。 I've tried to copy other answers and I just can't seem to get anywhere with the Network-Information plugin: https://github.com/apache/cordova-plugin-network-information
我试图复制其他答案,但似乎无法使用Network-Information插件获得任何帮助: https : //github.com/apache/cordova-plugin-network-information
At this point I really just want a barebones example of checking for a network connection at launch (onDeviceReady), and then a way to check again to see if the user's device has changed from online to offline and vice versa (seen some people suggest setTimeout for this piece). 在这一点上,我真的只想要一个准系统示例,该示例在启动时检查网络连接(onDeviceReady),然后再次检查用户的设备是否已从联机更改为脱机,反之亦然(见有人建议setTimeout)为此)。
After some testing, it seems like my navigator.connection.type check is not firing. 经过一些测试后,我的navigator.connection.type检查似乎没有启动。
I have the org.apache.cordova.network-inforamtion installed. 我安装了org.apache.cordova.network-inforamtion。 Please help... I've spent about a week pulling my hair out here.
请帮助...我花了大约一个星期的时间在这里拉头发。 :)
:)
My code: 我的代码:
<script type="text/javascript" src="js/ga.js">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is loaded and it is now safe to make calls Cordova methods
//
function onDeviceReady() {
checkConnection();
}
function checkConnection() {
var networkState = navigator.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';
alert('Connection type: ' + states[networkState]);
}
document.addEventListener("offline", onOffline, false);
function onOffline() {
// Handle the offline event
alert('Offline');
}
document.addEventListener("online", onOnline, false);
function onOnline() {
// Handle the online event
alert('Online');
}
</script>
Install network plugin org.apache.cordova.network-information and try the following:-
document.addEventListener("resume", getintoForeground, false);
function getintoForeground(){
var ntwk = CheckConnection();
if (ntwk) {
alert("Network available");
}else{
alert("Network not available");
}
}
function CheckConnection(){
if( !navigator.network ){
navigator.network = window.top.navigator.network;
}
return ( (navigator.network.connection.type === "none" || navigator.network.connection.type === null ||
navigator.network.connection.type === "unknown" ) ? false : true );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.