Android Open Source - incubator-cordova-android Geo Broker






From Project

Back to project page incubator-cordova-android.

License

The source code is released under:

Apache License

If you think the Android project incubator-cordova-android listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

/*
       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
//from   ww  w .j a v a 2  s .  c  o  m
         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.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.
 *
 * This class only starts and stops various GeoListeners, which consist of a GPS and a Network Listener
 */

public class GeoBroker extends Plugin {
    private GPSListener gpsListener;
    private NetworkListener networkListener;
    private LocationManager locationManager;

    /**
     * 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.cordova.getActivity().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);
    }

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

    /**
     * Called when the activity is to be shut down.
     * Stop listener.
     */
    public void onDestroy() {
        this.networkListener.destroy();
        this.gpsListener.destroy();
        this.networkListener = null;
        this.gpsListener = null;
    }

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

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




Java Source Code List

com.phonegap.api.IPlugin.java
com.phonegap.api.LOG.java
com.phonegap.api.PhonegapActivity.java
com.phonegap.api.PluginManager.java
com.phonegap.api.PluginResult.java
com.phonegap.api.Plugin.java
org.apache.cordova.AccelListener.java
org.apache.cordova.App.java
org.apache.cordova.AudioHandler.java
org.apache.cordova.AudioPlayer.java
org.apache.cordova.AuthenticationToken.java
org.apache.cordova.BatteryListener.java
org.apache.cordova.CallbackServer.java
org.apache.cordova.CameraLauncher.java
org.apache.cordova.Capture.java
org.apache.cordova.CompassListener.java
org.apache.cordova.ContactAccessorSdk5.java
org.apache.cordova.ContactAccessor.java
org.apache.cordova.ContactManager.java
org.apache.cordova.CordovaChromeClient.java
org.apache.cordova.CordovaLocationListener.java
org.apache.cordova.CordovaWebViewClient.java
org.apache.cordova.CordovaWebView.java
org.apache.cordova.Device.java
org.apache.cordova.DirectoryManager.java
org.apache.cordova.DroidGap.java
org.apache.cordova.ExifHelper.java
org.apache.cordova.FileTransfer.java
org.apache.cordova.FileUploadResult.java
org.apache.cordova.FileUtils.java
org.apache.cordova.GPSListener.java
org.apache.cordova.GeoBroker.java
org.apache.cordova.HttpHandler.java
org.apache.cordova.LinearLayoutSoftKeyboardDetect.java
org.apache.cordova.NetworkListener.java
org.apache.cordova.NetworkManager.java
org.apache.cordova.Notification.java
org.apache.cordova.SplashScreen.java
org.apache.cordova.StandAlone.java
org.apache.cordova.Storage.java
org.apache.cordova.TempListener.java
org.apache.cordova.api.CordovaInterface.java
org.apache.cordova.api.IPlugin.java
org.apache.cordova.api.LOG.java
org.apache.cordova.api.LegacyContext.java
org.apache.cordova.api.PluginEntry.java
org.apache.cordova.api.PluginManager.java
org.apache.cordova.api.PluginResult.java
org.apache.cordova.api.Plugin.java
org.apache.cordova.file.EncodingException.java
org.apache.cordova.file.FileExistsException.java
org.apache.cordova.file.InvalidModificationException.java
org.apache.cordova.file.NoModificationAllowedException.java
org.apache.cordova.file.TypeMismatchException.java