2

我正忙于学习 PhoneGap 并为 Android 构建应用程序。

得到基本的我的应用程序,设备准备好工作正常。

现在我正在尝试测试网络连接但没有成功。

我安装了插件网络信息:

$ cordova plugin add org.apache.cordova.network-information<br>
$ phonegap local plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-network-information.git<br>

向 config.xml 添加了功能:

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

一切都好。

当我做一个

$ phonegap local build android

它可以很好地构建应用程序。当我打开构建的 AndroidManifest.xml 文件时,会出现以下条目:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

当我运行应用程序时,我收到“ReferenceError:未定义连接”

这是我的代码,我从PhoneGap得到的:

try {
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';

alert('Connection type: ' + states[networkState]);
} catch (e) {
alert(e);
}

有没有人遇到过同样的问题,希望有解决方案?

4

1 回答 1

1

尝试添加超时功能来延迟navigator.connection.type通话。我遇到过同样的问题。这就是我解决它的方法:

首先执行以下操作:

var networkState = navigator.connection.type;

然后设置超时并navigator.connection.type再次运行:

setTimeout(function(){

    networkState = navigator.connection.type; // have to do this second time to pick up the refreshed value

    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';

    alert('Connection type: ' + states[networkState]);

}, 500);

我知道这很奇怪,但这给了 navigator.connection.type 时间(在本例中为 500 毫秒)来刷新它的值。它的行为就像是一个异步调用。

您可以尝试用更大或更小的值替换500 ms 。

于 2013-11-12T10:49:00.710 回答