javapenguin
javapenguin

Reputation: 1036

PhoneGap: ReferenceError: Connection is not defined

I'm busy learning PhoneGap and building an application for Android.

Got the basic my-app with device ready working fine.

Now I'm trying to test the network connection with no success.

I installed the 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>

Added feature to config.xml:

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

All OK.

When I do a

$ phonegap local build android

It builds the app fine. When I open the built AndroidManifest.xml file, the following entry is there:

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

When I run the app, I get a "ReferenceError: Connection is not defined"

Here is my code, I got this from 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);
}

Has anyone had the same problem and hopefully a solution?

Upvotes: 2

Views: 4011

Answers (1)

benka
benka

Reputation: 4742

Try to add a timeout function to delay the navigator.connection.type call. I had the same issue. This is how i solved it:

First do the:

var networkState = navigator.connection.type;

then set up a timeout and run the navigator.connection.type again:

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

I know it's strange but this gives time (500 ms in this example) to navigator.connection.type to refresh it's value. It acts like it was an async call.

You can experiment with replacing 500 ms with a bigger or smaller value.

Upvotes: 1

Related Questions