检查与phonegap的互联网连接 [英] check internet connection with phonegap

查看:153
本文介绍了检查与phonegap的互联网连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到几个不同的选项来检查与phonegap的互联网连接。有 document.addEventListener(online,onOnline,false); 还有 navigator.network.connection.type ...但我不知道哪一个是最佳实践。我也希望能够防止手机连接到WiFi网络但没有互联网连接的情况。

I am seeing a few different options to check internet connection with phonegap. There is document.addEventListener("online", onOnline, false); and there is also navigator.network.connection.type... but I am not sure which one is best practice. I would also like to be able to prevent the bad case where the phone is connected to a wifi network but has no internet connection.

$(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,但我们不确定

For example, this code works if the phone is connected to the wifi, but we are not sure the internet is actually available.

有关Phonegap 3.3+和Jquery mobile 1.4的最佳做法是什么?

What are the best practices with phonegap 3.3+ and Jquery mobile 1.4 ?

推荐答案

document.addEventListener("online", onOnline, false);

仅在应用程序已加载并重新连接时触发。

is only fired when your app is already is loaded and regains a connection. This is not fired on start of the application.

因此,您必须使用 checkConnection()方法启动应用程序,然后如果您需要稍后在应用程序运行时检查,请使用事件侦听器。

Therefore, you have to use the checkConnection() method on start of your application and then if you need to check later while the app is running, you use the event listener.

这篇关于检查与phonegap的互联网连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆