1

我试图确定应用程序启动时设备是否已连接到互联网。据我所知,javascript代码应该是这样的:

function isOnline() {
    var networkState = navigator.network.connection.type;
    if (networkState == Connection.NONE) {
        return false;
    };
    return true;
}

到目前为止,我只在 iOS 上尝试过。不幸的是, navigator.network 是未定义的。

我知道我必须在 config.xml 文件中添加网络模块。根据 PhoneGap 页面(http://docs.phonegap.com/en/3.0.0/cordova_connection_connection.md.html),我就是这样做的:

<feature name="NetworkStatus">
    <param name="ios-package" value="CDVConnection" />
</feature>

<feature name="NetworkStatus">
    <param name="android-package" value="org.apache.cordova.NetworkManager" />
</feature>

有人知道我错过了什么吗?

4

2 回答 2

2

试试这个。

在此处安装此科尔多瓦插件。

https://github.com/apache/cordova-plugin-network-information

并将此代码添加到 js 文件中

document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//

function onDeviceReady() {
    isOnline();
}

function isOnline() {
    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.CELL] = 'Cell generic connection';
    states[Connection.NONE] = 'No network connection';
    if ((states[networkState]) == states[Connection.NONE]) {
        alert('No Internet Connection. Click OK to exit app');
        navigator.app.exitApp();
    }
}
于 2014-04-09T12:20:02.093 回答
0

试试这个:

function checkConnection() {
        return navigator.connection.type === "none" || navigator.network.connection.type === null ||
                navigator.connection.type === "unknown" ? false : true;
    }

并且记得在设备就绪事件触发后检查这个。

于 2014-04-08T21:10:17.897 回答