Merging master into CordovaWebView

This commit is contained in:
Joe Bowser 2012-05-11 10:36:17 -07:00
commit fc9cff7d26
12 changed files with 362 additions and 585 deletions

1
.gitignore vendored
View File

@ -17,3 +17,4 @@ example
tmp
*.tmp
test/libs/*.jar
bin/node_modules

View File

@ -31,6 +31,7 @@ Building
---
To create your cordova.jar, copy the commons codec:
mv commons-codec-1.6.jar framework/libs
then run in the framework directory:

View File

@ -1,21 +1,3 @@
/*
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.
*/
{
"name": "cordova-android-cli",
"description": "CLI tooling for the cordova-android project",
@ -42,4 +24,3 @@
"nodeunit":"0.5.3"
}
}

View File

@ -1,6 +1,6 @@
// commit 9a080cc2704171a4169739b2c94ca55427b92f93
// commit 55e46cecd73e06a4866f084ffa8513219ef68421
// File generated at :: Thu May 10 2012 15:48:14 GMT-0700 (PDT)
// File generated at :: Fri May 11 2012 10:34:50 GMT-0700 (PDT)
/*
Licensed to the Apache Software Foundation (ASF) under one
@ -98,17 +98,7 @@ var documentEventHandlers = {},
document.addEventListener = function(evt, handler, capture) {
var e = evt.toLowerCase();
if (e == 'deviceready') {
channel.onDeviceReady.subscribeOnce(handler);
} else if (e == 'resume') {
channel.onResume.subscribe(handler);
// if subscribing listener after event has already fired, invoke the handler
if (channel.onResume.fired && typeof handler == 'function') {
handler();
}
} else if (e == 'pause') {
channel.onPause.subscribe(handler);
} else if (typeof documentEventHandlers[e] != 'undefined') {
if (typeof documentEventHandlers[e] != 'undefined') {
documentEventHandlers[e].subscribe(handler);
} else {
m_document_addEventListener.call(document, evt, handler, capture);
@ -126,13 +116,8 @@ window.addEventListener = function(evt, handler, capture) {
document.removeEventListener = function(evt, handler, capture) {
var e = evt.toLowerCase();
// Check for pause/resume events first.
if (e == 'resume') {
channel.onResume.unsubscribe(handler);
} else if (e == 'pause') {
channel.onPause.unsubscribe(handler);
// If unsubcribing from an event that is handled by a plugin
} else if (typeof documentEventHandlers[e] != "undefined") {
if (typeof documentEventHandlers[e] != "undefined") {
documentEventHandlers[e].unsubscribe(handler);
} else {
m_document_removeEventListener.call(document, evt, handler, capture);
@ -318,6 +303,11 @@ var cordova = {
}
};
// Register pause, resume and deviceready channels as events on document.
channel.onPause = cordova.addDocumentEventHandler('pause');
channel.onResume = cordova.addDocumentEventHandler('resume');
channel.onDeviceReady = cordova.addDocumentEventHandler('deviceready');
// Adds deprecation warnings to functions of an object (but only logs a message once)
function deprecateFunctions(obj, objLabel) {
var newObj = {};
@ -1101,7 +1091,7 @@ module.exports = {
// Let native code know we are all done on the JS side.
// Native code will then un-hide the WebView.
channel.join(function() {
exec(function(){}, function(){}, 'App', 'show', []);
prompt("", "gap_init:");
}, [channel.onCordovaReady]);
},
objects: {
@ -5182,7 +5172,7 @@ window.cordova = require('cordova');
// Fire onDeviceReady event once all constructors have run and
// cordova info has been received from native side.
channel.join(function() {
channel.onDeviceReady.fire();
require('cordova').fireDocumentEvent('deviceready');
}, channel.deviceReadyChannelsArray);
}, [ channel.onDOMContentLoaded, channel.onNativeReady ]);
@ -5201,4 +5191,5 @@ window.cordova = require('cordova');
}(window));
})();

View File

@ -10,5 +10,5 @@
# Indicates whether an apk should be generated for each density.
split.density=false
# Project target.
target=android-15
target=Google Inc.:Google APIs:15
apk-configurations=

View File

@ -0,0 +1,198 @@
/*
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.
*/
package org.apache.cordova;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
public class CordovaLocationListener implements LocationListener {
public static int PERMISSION_DENIED = 1;
public static int POSITION_UNAVAILABLE = 2;
public static int TIMEOUT = 3;
protected LocationManager locationManager;
private GeoBroker owner;
protected boolean running = false;
public HashMap<String, String> watches = new HashMap<String, String>();
private List<String> callbacks = new ArrayList<String>();
private String TAG = "[Cordova Location Listener]";
public CordovaLocationListener(LocationManager manager, GeoBroker broker, String tag) {
this.locationManager = manager;
this.owner = broker;
this.TAG = tag;
}
protected void fail(int code, String message) {
for (String callbackId: this.callbacks)
{
this.owner.fail(code, message, callbackId);
}
this.callbacks.clear();
Iterator it = this.watches.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
this.owner.fail(code, message, (String)pairs.getValue());
}
}
private void win(Location loc) {
for (String callbackId: this.callbacks)
{
this.owner.win(loc, callbackId);
}
this.callbacks.clear();
Iterator it = this.watches.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
this.owner.win(loc, (String)pairs.getValue());
}
}
/**
* Location Listener Methods
*/
/**
* Called when the provider is disabled by the user.
*
* @param provider
*/
public void onProviderDisabled(String provider) {
Log.d(TAG, "Location provider '" + provider + "' disabled.");
this.fail(POSITION_UNAVAILABLE, "GPS provider disabled.");
}
/**
* Called when the provider is enabled by the user.
*
* @param provider
*/
public void onProviderEnabled(String provider) {
Log.d(TAG, "Location provider "+ provider + " has been enabled");
}
/**
* Called when the provider status changes. This method is called when a
* provider is unable to fetch a location or if the provider has recently
* become available after a period of unavailability.
*
* @param provider
* @param status
* @param extras
*/
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "The status of the provider " + provider + " has changed");
if (status == 0) {
Log.d(TAG, provider + " is OUT OF SERVICE");
this.fail(CordovaLocationListener.POSITION_UNAVAILABLE, "Provider " + provider + " is out of service.");
}
else if (status == 1) {
Log.d(TAG, provider + " is TEMPORARILY_UNAVAILABLE");
}
else {
Log.d(TAG, provider + " is AVAILABLE");
}
}
/**
* Called when the location has changed.
*
* @param location
*/
public void onLocationChanged(Location location) {
Log.d(TAG, "The location has been updated!");
this.win(location);
}
// PUBLIC
public int size() {
return this.watches.size() + this.callbacks.size();
}
public void addWatch(String timerId, String callbackId) {
this.watches.put(timerId, callbackId);
if (this.size() == 1) {
this.start();
}
}
public void addCallback(String callbackId) {
this.callbacks.add(callbackId);
if (this.size() == 1) {
this.start();
}
}
public void clearWatch(String timerId) {
if (this.watches.containsKey(timerId)) {
this.watches.remove(timerId);
}
if (this.size() == 0) {
this.stop();
}
}
/**
* Destroy listener.
*/
public void destroy() {
this.stop();
}
// LOCAL
/**
* Start requesting location updates.
*
* @param interval
*/
protected void start() {
if (!this.running) {
if (this.locationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
this.running = true;
this.locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 10, this);
} else {
this.fail(CordovaLocationListener.POSITION_UNAVAILABLE, "Network provider is not available.");
}
}
}
/**
* Stop receiving location updates.
*/
private void stop() {
if (this.running) {
this.locationManager.removeUpdates(this);
this.running = false;
}
}
}

View File

@ -659,7 +659,7 @@ public class DroidGap extends Activity implements CordovaInterface {
}
// Send pause event to JavaScript
this.appView.loadUrl("javascript:try{cordova.require('cordova/channel').onPause.fire();}catch(e){console.log('exception firing pause event from native');};");
this.appView.loadUrl("javascript:try{cordova.fireDocumentEvent('pause');}catch(e){console.log('exception firing pause event from native');};");
// Forward to plugins
appView.pluginManager.onPause(this.keepRunning);
@ -700,7 +700,7 @@ public class DroidGap extends Activity implements CordovaInterface {
}
// Send resume event to JavaScript
this.appView.loadUrl("javascript:try{cordova.require('cordova/channel').onResume.fire();}catch(e){console.log('exception firing resume event from native');};");
this.appView.loadUrl("javascript:try{cordova.fireDocumentEvent('resume');}catch(e){console.log('exception firing resume event from native');};");
// Forward to plugins
appView.pluginManager.onResume(this.keepRunning || this.activityResultKeepRunning);

View File

@ -222,9 +222,10 @@ public class FileUtils extends Plugin {
* @param filePath the path to check
*/
private void notifyDelete(String filePath) {
String newFilePath = filePath.substring(7);
int result = this.ctx.getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
MediaStore.Images.Media.DATA + " = ?",
new String[] {filePath});
new String[] {newFilePath});
}
/**

View File

@ -18,14 +18,15 @@
*/
package org.apache.cordova;
import java.util.HashMap;
import java.util.Map.Entry;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
/*
* This class is the interface to the Geolocation. It's bound to the geo object.
@ -34,132 +35,152 @@ import org.json.JSONException;
*/
public class GeoBroker extends Plugin {
// List of gGeolocation listeners
private HashMap<String, GeoListener> geoListeners;
private GeoListener global;
private GPSListener gpsListener;
private NetworkListener networkListener;
private LocationManager locationManager;
/**
* Constructor.
*/
public GeoBroker() {
this.geoListeners = new HashMap<String, GeoListener>();
/**
* Constructor.
*/
public GeoBroker() {
}
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public PluginResult execute(String action, JSONArray args, String callbackId) {
if (this.locationManager == null) {
this.locationManager = (LocationManager) this.ctx.getSystemService(Context.LOCATION_SERVICE);
this.networkListener = new NetworkListener(this.locationManager, this);
this.gpsListener = new GPSListener(this.locationManager, this);
}
PluginResult.Status status = PluginResult.Status.NO_RESULT;
String message = "";
PluginResult result = new PluginResult(status, message);
result.setKeepCallback(true);
try {
if (action.equals("getLocation")) {
boolean enableHighAccuracy = args.getBoolean(0);
int maximumAge = args.getInt(1);
Location last = this.locationManager.getLastKnownLocation((enableHighAccuracy ? LocationManager.GPS_PROVIDER : LocationManager.NETWORK_PROVIDER));
// Check if we can use lastKnownLocation to get a quick reading and use less battery
if ((System.currentTimeMillis() - last.getTime()) <= maximumAge) {
result = new PluginResult(PluginResult.Status.OK, this.returnLocationJSON(last));
} else {
this.getCurrentLocation(callbackId, enableHighAccuracy);
}
}
else if (action.equals("addWatch")) {
String id = args.getString(0);
boolean enableHighAccuracy = args.getBoolean(1);
this.addWatch(id, callbackId, enableHighAccuracy);
}
else if (action.equals("clearWatch")) {
String id = args.getString(0);
this.clearWatch(id);
}
} catch (JSONException e) {
result = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage());
}
return result;
}
private void clearWatch(String id) {
this.gpsListener.clearWatch(id);
this.networkListener.clearWatch(id);
}
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
try {
if (action.equals("getCurrentLocation")) {
this.getCurrentLocation(args.getBoolean(0), args.getInt(1), args.getInt(2));
}
else if (action.equals("start")) {
String s = this.start(args.getString(0), args.getBoolean(1), args.getInt(2), args.getInt(3));
return new PluginResult(status, s);
}
else if (action.equals("stop")) {
this.stop(args.getString(0));
}
return new PluginResult(status, result);
} catch (JSONException e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
private void getCurrentLocation(String callbackId, boolean enableHighAccuracy) {
if (enableHighAccuracy) {
this.gpsListener.addCallback(callbackId);
} else {
this.networkListener.addCallback(callbackId);
}
}
private void addWatch(String timerId, String callbackId, boolean enableHighAccuracy) {
if (enableHighAccuracy) {
this.gpsListener.addWatch(timerId, callbackId);
} else {
this.networkListener.addWatch(timerId, callbackId);
}
}
/**
* Identifies if action to be executed returns a value and should be run synchronously.
*
* @param action The action to execute
* @return T=returns value
*/
public boolean isSynch(String action) {
// Starting listeners is easier to run on main thread, so don't run async.
return true;
}
* Identifies if action to be executed returns a value and should be run synchronously.
*
* @param action The action to execute
* @return T=returns value
*/
public boolean isSynch(String action) {
// Starting listeners is easier to run on main thread, so don't run async.
return true;
}
/**
* Called when the activity is to be shut down.
* Stop listener.
*/
public void onDestroy() {
java.util.Set<Entry<String,GeoListener>> s = this.geoListeners.entrySet();
java.util.Iterator<Entry<String,GeoListener>> it = s.iterator();
while (it.hasNext()) {
Entry<String,GeoListener> entry = it.next();
GeoListener listener = entry.getValue();
listener.destroy();
}
this.geoListeners.clear();
if (this.global != null) {
this.global.destroy();
}
this.global = null;
this.networkListener.destroy();
this.gpsListener.destroy();
this.networkListener = null;
this.gpsListener = null;
}
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
/**
* Get current location.
* The result is returned to JavaScript via a callback.
*
* @param enableHighAccuracy
* @param timeout
* @param maximumAge
*/
public void getCurrentLocation(boolean enableHighAccuracy, int timeout, int maximumAge) {
// Create a geolocation listener just for getCurrentLocation and call it "global"
if (this.global == null) {
this.global = new GeoListener(this, "global", maximumAge);
public JSONObject returnLocationJSON(Location loc) {
JSONObject o = new JSONObject();
try {
o.put("latitude", loc.getLatitude());
o.put("longitude", loc.getLongitude());
o.put("altitude", (loc.hasAltitude() ? loc.getAltitude() : null));
o.put("accuracy", loc.getAccuracy());
o.put("heading", (loc.hasBearing() ? (loc.hasSpeed() ? loc.getBearing() : null) : null));
o.put("speed", loc.getSpeed());
o.put("timestamp", loc.getTime());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
else {
this.global.start(maximumAge);
}
}
/**
* Start geolocation listener and add to listener list.
*
* @param key The listener id
* @param enableHighAccuracy
* @param timeout
* @param maximumAge
* @return
*/
public String start(String key, boolean enableHighAccuracy, int timeout, int maximumAge) {
// Make sure this listener doesn't already exist
GeoListener listener = geoListeners.get(key);
if (listener == null) {
listener = new GeoListener(this, key, maximumAge);
geoListeners.put(key, listener);
}
// Start it
listener.start(maximumAge);
return key;
}
/**
* Stop geolocation listener and remove from listener list.
*
* @param key The listener id
*/
public void stop(String key) {
GeoListener listener = geoListeners.remove(key);
if (listener != null) {
listener.stop();
}
}
return o;
}
public void win(Location loc, String callbackId) {
PluginResult result = new PluginResult(PluginResult.Status.OK, this.returnLocationJSON(loc));
this.success(result, callbackId);
}
/**
* Location failed. Send error back to JavaScript.
*
* @param code The error code
* @param msg The error message
* @throws JSONException
*/
public void fail(int code, String msg, String callbackId) {
JSONObject obj = new JSONObject();
String backup = null;
try {
obj.put("code", code);
obj.put("message", msg);
} catch (JSONException e) {
obj = null;
backup = "{'code':" + code + ",'message':'" + msg.replaceAll("'", "\'") + "'}";
}
PluginResult result;
if (obj != null) {
result = new PluginResult(PluginResult.Status.ERROR, obj);
} else {
result = new PluginResult(PluginResult.Status.ERROR, backup);
}
this.error(result, callbackId);
}
}

View File

@ -1,133 +0,0 @@
/*
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.
*/
package org.apache.cordova;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.webkit.WebView;
public class GeoListener {
public static int PERMISSION_DENIED = 1;
public static int POSITION_UNAVAILABLE = 2;
public static int TIMEOUT = 3;
String id; // Listener ID
String successCallback; //
String failCallback;
GpsListener mGps; // GPS listener
NetworkListener mNetwork; // Network listener
LocationManager mLocMan; // Location manager
private GeoBroker broker; // GeoBroker object
int interval;
/**
* Constructor.
*
* @param id Listener id
* @param ctx
* @param time Sampling period in msec
* @param appView
*/
GeoListener(GeoBroker broker, String id, int time) {
this.id = id;
this.interval = time;
this.broker = broker;
this.mGps = null;
this.mNetwork = null;
this.mLocMan = (LocationManager) broker.ctx.getSystemService(Context.LOCATION_SERVICE);
// If GPS provider, then create and start GPS listener
if (this.mLocMan.getProvider(LocationManager.GPS_PROVIDER) != null) {
this.mGps = new GpsListener(broker.ctx, time, this);
}
// If network provider, then create and start network listener
if (this.mLocMan.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
this.mNetwork = new NetworkListener(broker.ctx, time, this);
}
}
/**
* Destroy listener.
*/
public void destroy() {
this.stop();
}
/**
* Location found. Send location back to JavaScript.
*
* @param loc
*/
void success(Location loc) {
String params = loc.getLatitude() + "," + loc.getLongitude() + ", " + loc.getAltitude() +
"," + loc.getAccuracy() + "," + loc.getBearing() +
"," + loc.getSpeed() + "," + loc.getTime();
if (id == "global") {
this.stop();
}
this.broker.sendJavascript("navigator._geo.success('" + id + "'," + params + ");");
}
/**
* Location failed. Send error back to JavaScript.
*
* @param code The error code
* @param msg The error message
*/
void fail(int code, String msg) {
this.broker.sendJavascript("navigator._geo.fail('" + this.id + "', '" + code + "', '" + msg + "');");
this.stop();
}
/**
* Start retrieving location.
*
* @param interval
*/
void start(int interval) {
if (this.mGps != null) {
this.mGps.start(interval);
}
if (this.mNetwork != null) {
this.mNetwork.start(interval);
}
if (this.mNetwork == null && this.mGps == null) {
this.fail(POSITION_UNAVAILABLE, "No location providers available.");
}
}
/**
* Stop listening for location.
*/
void stop() {
if (this.mGps != null) {
this.mGps.stop();
}
if (this.mNetwork != null) {
this.mNetwork.stop();
}
}
}

View File

@ -1,163 +0,0 @@
/*
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.
*/
package org.apache.cordova;
import org.apache.cordova.api.CordovaInterface;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationListener;
import android.os.Bundle;
/**
* This class handles requests for GPS location services.
*
*/
public class GpsListener implements LocationListener {
private Context mCtx; // CordovaActivity object
private LocationManager mLocMan; // Location manager object
private GeoListener owner; // Geolistener object (parent)
private boolean hasData = false; // Flag indicates if location data is available in cLoc
private Location cLoc; // Last recieved location
private boolean running = false; // Flag indicates if listener is running
/**
* Constructor.
* Automatically starts listening.
*
* @param ctx
* @param interval
* @param m
*/
public GpsListener(Context ctx, int interval, GeoListener m) {
this.owner = m;
this.mCtx = ctx;
this.mLocMan = (LocationManager) this.mCtx.getSystemService(Context.LOCATION_SERVICE);
this.running = false;
this.start(interval);
}
/**
* Get last location.
*
* @return Location object
*/
public Location getLocation() {
this.cLoc = this.mLocMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (this.cLoc != null) {
this.hasData = true;
}
return this.cLoc;
}
/**
* Called when the provider is disabled by the user.
*
* @param provider
*/
public void onProviderDisabled(String provider) {
this.owner.fail(GeoListener.POSITION_UNAVAILABLE, "GPS provider disabled.");
}
/**
* Called when the provider is enabled by the user.
*
* @param provider
*/
public void onProviderEnabled(String provider) {
System.out.println("GpsListener: The provider "+ provider + " is enabled");
}
/**
* Called when the provider status changes. This method is called when a
* provider is unable to fetch a location or if the provider has recently
* become available after a period of unavailability.
*
* @param provider
* @param status
* @param extras
*/
public void onStatusChanged(String provider, int status, Bundle extras) {
System.out.println("GpsListener: The status of the provider " + provider + " has changed");
if (status == 0) {
System.out.println("GpsListener: " + provider + " is OUT OF SERVICE");
this.owner.fail(GeoListener.POSITION_UNAVAILABLE, "GPS out of service.");
}
else if (status == 1) {
System.out.println("GpsListener: " + provider + " is TEMPORARILY_UNAVAILABLE");
}
else {
System.out.println("GpsListener: " + provider + " is Available");
}
}
/**
* Called when the location has changed.
*
* @param location
*/
public void onLocationChanged(Location location) {
System.out.println("GpsListener: The location has been updated!");
this.hasData = true;
this.cLoc = location;
this.owner.success(location);
}
/**
* Determine if location data is available.
*
* @return
*/
public boolean hasLocation() {
return this.hasData;
}
/**
* Start requesting location updates.
*
* @param interval
*/
public void start(int interval) {
if (!this.running) {
this.running = true;
this.mLocMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, interval, 0, this);
this.getLocation();
// If GPS provider has data, then send now
if (this.hasData) {
this.owner.success(this.cLoc);
}
}
}
/**
* Stop receiving location updates.
*/
public void stop() {
if (this.running) {
this.mLocMan.removeUpdates(this);
}
this.running = false;
}
}

View File

@ -16,138 +16,17 @@
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova;
import org.apache.cordova.api.CordovaInterface;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationListener;
import android.os.Bundle;
public class NetworkListener implements LocationListener {
private Context mCtx; // CordovaActivity object
private LocationManager mLocMan; // Location manager object
private GeoListener owner; // Geolistener object (parent)
private boolean hasData = false; // Flag indicates if location data is available in cLoc
private Location cLoc; // Last recieved location
private boolean running = false; // Flag indicates if listener is running
/**
* Constructor.
* Automatically starts listening.
*
* @param ctx
* @param interval
* @param m
*/
public NetworkListener(Context ctx, int interval, GeoListener m) {
this.owner = m;
this.mCtx = ctx;
this.mLocMan = (LocationManager) this.mCtx.getSystemService(Context.LOCATION_SERVICE);
this.running = false;
this.start(interval);
}
/**
* Get last location.
*
* @return Location object
*/
public Location getLocation() {
this.cLoc = this.mLocMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (this.cLoc != null) {
this.hasData = true;
}
return this.cLoc;
}
/**
* Called when the provider is disabled by the user.
*
* @param provider
*/
public void onProviderDisabled(String provider) {
System.out.println("NetworkListener: The provider " + provider + " is disabled");
}
/**
* Called when the provider is enabled by the user.
*
* @param provider
*/
public void onProviderEnabled(String provider) {
System.out.println("NetworkListener: The provider "+ provider + " is enabled");
}
/**
* Called when the provider status changes. This method is called when a
* provider is unable to fetch a location or if the provider has recently
* become available after a period of unavailability.
*
* @param provider
* @param status
* @param extras
*/
public void onStatusChanged(String provider, int status, Bundle extras) {
System.out.println("NetworkListener: The status of the provider " + provider + " has changed");
if (status == 0) {
System.out.println("NetworkListener: " + provider + " is OUT OF SERVICE");
}
else if (status == 1) {
System.out.println("NetworkListener: " + provider + " is TEMPORARILY_UNAVAILABLE");
}
else {
System.out.println("NetworkListener: " + provider + " is Available");
}
}
/**
* Called when the location has changed.
*
* @param location
*/
public void onLocationChanged(Location location) {
System.out.println("NetworkListener: The location has been updated!");
this.hasData = true;
this.cLoc = location;
// The GPS is the primary form of Geolocation in Cordova.
// Only fire the success variables if the GPS is down for some reason.
if (!this.owner.mGps.hasLocation()) {
this.owner.success(location);
}
}
/**
* Start requesting location updates.
*
* @param interval
*/
public void start(int interval) {
if (!this.running) {
this.running = true;
this.mLocMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, interval, 0, this);
this.getLocation();
// If Network provider has data but GPS provider doesn't, then send ours
if (this.hasData && !this.owner.mGps.hasLocation()) {
this.owner.success(this.cLoc);
}
}
}
/**
* Stop receiving location updates.
*/
public void stop() {
if (this.running) {
this.mLocMan.removeUpdates(this);
}
this.running = false;
}
/**
* This class handles requests for GPS location services.
*
*/
public class NetworkListener extends CordovaLocationListener {
public NetworkListener(LocationManager locationManager, GeoBroker m) {
super(locationManager, m, "[Cordova NetworkListener]");
}
}