cordova-android/framework/assets/js/network.js
2012-02-03 10:38:40 -05:00

101 lines
3.4 KiB
JavaScript
Executable File

/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
if (!Cordova.hasResource("network")) {
Cordova.addResource("network");
/**
* This class contains information about the current network Connection.
* @constructor
*/
var Connection = function() {
this.type = null;
this._firstRun = true;
this._timer = null;
this.timeout = 500;
var me = this;
this.getInfo(
function(type) {
// Need to send events if we are on or offline
if (type === "none") {
// set a timer if still offline at the end of timer send the offline event
me._timer = setTimeout(function(){
me.type = type;
Cordova.fireDocumentEvent('offline');
me._timer = null;
}, me.timeout);
} else {
// If there is a current offline event pending clear it
if (me._timer !== null) {
clearTimeout(me._timer);
me._timer = null;
}
me.type = type;
Cordova.fireDocumentEvent('online');
}
// should only fire this once
if (me._firstRun) {
me._firstRun = false;
Cordova.onCordovaConnectionReady.fire();
}
},
function(e) {
// If we can't get the network info we should still tell Cordova
// to fire the deviceready event.
if (me._firstRun) {
me._firstRun = false;
Cordova.onCordovaConnectionReady.fire();
}
console.log("Error initializing Network Connection: " + e);
});
};
Connection.UNKNOWN = "unknown";
Connection.ETHERNET = "ethernet";
Connection.WIFI = "wifi";
Connection.CELL_2G = "2g";
Connection.CELL_3G = "3g";
Connection.CELL_4G = "4g";
Connection.NONE = "none";
/**
* Get connection info
*
* @param {Function} successCallback The function to call when the Connection data is available
* @param {Function} errorCallback The function to call when there is an error getting the Connection data. (OPTIONAL)
*/
Connection.prototype.getInfo = function(successCallback, errorCallback) {
// Get info
Cordova.exec(successCallback, errorCallback, "Network Status", "getConnectionInfo", []);
};
Cordova.addConstructor(function() {
if (typeof navigator.network === "undefined") {
navigator.network = {};
}
if (typeof navigator.network.connection === "undefined") {
navigator.network.connection = new Connection();
}
});
}