PhoneGap:ReferenceError:未定义连接

时间:2013-11-12 10:04:02

标签: javascript android cordova

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

获得基本的my-app,设备就绪正常。

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

我安装了plugin-network-information:

$ 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);
}

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

1 个答案:

答案 0 :(得分: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