Example usage for android.location Location getAccuracy

List of usage examples for android.location Location getAccuracy

Introduction

In this page you can find the example usage for android.location Location getAccuracy.

Prototype

public float getAccuracy() 

Source Link

Document

Get the estimated horizontal accuracy of this location, radial, in meters.

Usage

From source file:com.barkside.travellocblog.LocationUpdates.java

/** Determines whether one Location reading is better than the current Location fix
 *
 * From http://developer.android.com/guide/topics/location/strategies.html
 * //  w  w w. ja  va2  s .  com
 * http://developer.android.com/guide/topics/location/strategies.html
 * @param location  The new Location that you want to evaluate
 * @param currentBestLocation  The current Location fix, to which you want to compare the new one
 */
public static boolean isBetterLocation(Location location, Location currentBestLocation) {
    if (currentBestLocation == null) {
        // A new location is always better than no location
        return true;
    }

    // Check whether the new location fix is newer or older
    long timeDelta = location.getTime() - currentBestLocation.getTime();
    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
    boolean isNewer = timeDelta > 0;

    // If it's been more than two minutes since the current location, use the new location
    // because the user has likely moved
    if (isSignificantlyNewer) {
        return true;
        // If the new location is more than two minutes older, it must be worse
    } else if (isSignificantlyOlder) {
        return false;
    }

    // Check whether the new location fix is more or less accurate
    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
    boolean isLessAccurate = accuracyDelta > 0;
    boolean isMoreAccurate = accuracyDelta < 0;
    boolean isSignificantlyLessAccurate = accuracyDelta > 200;

    // Check if the old and new location are from the same provider
    boolean isFromSameProvider = isSameProvider(location.getProvider(), currentBestLocation.getProvider());

    // Determine location quality using a combination of timeliness and accuracy
    if (isMoreAccurate) {
        return true;
    } else if (isNewer && !isLessAccurate) {
        return true;
    } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
        return true;
    }
    return false;
}

From source file:org.akvo.rsr.up.UpdateEditorActivity.java

/**
 * populates the fields on the UI with the location info from the event
 * // w ww.j  a v  a  2  s . c o m
 * @param loc
 */
private void populateLocation(Location loc) {
    if (loc.hasAccuracy()) {
        accuracyField.setText(new DecimalFormat("#").format(loc.getAccuracy()) + " m");
        if (loc.getAccuracy() <= ACCURACY_THRESHOLD) {
            accuracyField.setTextColor(Color.GREEN);
        } else {
            accuracyField.setTextColor(Color.RED);
        }
    }
    latField.setText(loc.getLatitude() + "");
    lonField.setText(loc.getLongitude() + "");
    // elevation is in meters, even one decimal is way more than GPS precision
    eleField.setText(new DecimalFormat("#.#").format(loc.getAltitude()));
}

From source file:carsharing.starter.automotive.iot.ibm.com.mobilestarterapp.AnalyzeMyDriving.java

private boolean checkCurrentLocation() {
    if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(),
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(),
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return false;
    }//w  w  w . j a  va 2 s.  c  o  m
    locationManager = (LocationManager) getActivity().getApplicationContext()
            .getSystemService(Context.LOCATION_SERVICE);

    final List<String> providers = locationManager.getProviders(true);
    Location finalLocation = null;

    for (final String provider : providers) {
        final Location lastKnown = locationManager.getLastKnownLocation(provider);
        if (lastKnown == null) {
            continue;
        }
        if (finalLocation == null || (lastKnown.getAccuracy() < finalLocation.getAccuracy())) {
            finalLocation = lastKnown;
        }
    }
    location = finalLocation;
    return location != null;
}

From source file:com.tagaugmentedreality.utilties.LocationRetriever.java

@Override
public void onConnected(Bundle arg0) {

    if (null != mLocationClient) {
        //Toast.makeText(this.context, "Connected", Toast.LENGTH_SHORT).show();
        Location mCurrentLocation = mLocationClient.getLastLocation();
        if (null != mCurrentLocation) {
            latitude = mCurrentLocation.getLatitude();
            longitude = mCurrentLocation.getLongitude();

            //Toast.makeText(this.context, latitude.toString()+" "+longitude.toString(),Toast.LENGTH_SHORT).show();
            mLocationClient.requestLocationUpdates(mLocationRequest, this);
            Log.e("last",
                    latitude.toString() + " " + longitude.toString() + " " + mCurrentLocation.getAccuracy());
        } //end if
        else {/*from w w w . ja  va2 s. c om*/
            connectToClient();
        } //end else

    } //end if
    else {
        mLocationClient = new LocationClient(context, this, this);
        connectToClient();

    } //end else

}

From source file:com.prey.actions.geofences.GeofenceIntentService.java

private void notifyGeofenceTransition(Context context, int geofenceTransition,
        List<Geofence> triggeringGeofences, Location location) {
    PreyLogger.d("notifyGeofenceTransition");
    ArrayList triggeringGeofencesIdsList = new ArrayList();
    for (Geofence geofence : triggeringGeofences) {
        PreyLogger.d("geofence.getRequestId():" + geofence.getRequestId());
        triggeringGeofencesIdsList.add(geofence.getRequestId());
        try {/*from w  ww .j a v a2s  .  c o m*/
            Event event = new Event();
            if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER)
                event.setName("geofencing_in");
            else
                event.setName("geofencing_out");
            JSONObject info = new JSONObject();
            info.put("id", Integer.parseInt(geofence.getRequestId()));
            info.put("lat", location.getLatitude());
            info.put("lng", location.getLongitude());
            info.put("accuracy", location.getAccuracy());
            info.put("method", "native");
            event.setInfo(info.toString());
            JSONObject jsonObjectStatus = new JSONObject();
            int geofenceMaximumAccuracy = PreyConfig.getPreyConfig(context).getGeofenceMaximumAccuracy();
            if (location.getAccuracy() <= geofenceMaximumAccuracy) {
                new EventThread(this, event, jsonObjectStatus).start();
            } else {
                PreyLogger.d("MaximumAccuracy:" + location.getAccuracy());
            }
        } catch (Exception e) {
            PreyLogger.e("notifyGeofenceTransition error:" + e.getMessage(), e);
        }
    }
}

From source file:in.rade.armud.armudclient.MainActivity.java

/**
 * Communicate with MUD over websocket/* w  w w  . jav a 2s.c  o  m*/
 */
public void talkwithMUD(final Location location) {
    if (null == location) {
        Toast.makeText(this, "Make sure location is turned on!", Toast.LENGTH_LONG);
    } else if (mConnected) {
        String querystring = "location " + location.getLatitude() + " " + location.getLongitude() + " "
                + location.getAccuracy();
        client.send(querystring);
    }
}

From source file:com.marianhello.cordova.bgloc.LocationUpdateService.java

public void onLocationChanged(Location location) {
        Log.d(TAG, "- onLocationChanged: " + location.getLatitude() + "," + location.getLongitude() + ", accuracy: "
                + location.getAccuracy() + ", isMoving: " + isMoving + ", speed: " + location.getSpeed());

        if (!isMoving && !isAcquiringStationaryLocation && stationaryLocation == null) {
            // Perhaps our GPS signal was interupted, re-acquire a stationaryLocation now.
            setPace(false);//from  w w w . j  a v a2 s. c om
        }

        if (isDebugging) {
            Toast.makeText(this, "mv:" + isMoving + ",acy:" + location.getAccuracy() + ",v:" + location.getSpeed()
                    + ",df:" + scaledDistanceFilter, Toast.LENGTH_LONG).show();
        }
        if (isAcquiringStationaryLocation) {
            if (stationaryLocation == null || stationaryLocation.getAccuracy() > location.getAccuracy()) {
                stationaryLocation = location;
            }
            if (++locationAcquisitionAttempts == MAX_STATIONARY_ACQUISITION_ATTEMPTS) {
                isAcquiringStationaryLocation = false;
                startMonitoringStationaryRegion(stationaryLocation);
                if (isDebugging) {
                    startTone("long_beep");
                }
            } else {
                // Unacceptable stationary-location: bail-out and wait for another.
                if (isDebugging) {
                    startTone("beep");
                }
                return;
            }
        } else if (isAcquiringSpeed) {
            if (++locationAcquisitionAttempts == MAX_SPEED_ACQUISITION_ATTEMPTS) {
                // Got enough samples, assume we're confident in reported speed now.  Play "woohoo" sound.
                if (isDebugging) {
                    startTone("doodly_doo");
                }
                isAcquiringSpeed = false;
                scaledDistanceFilter = calculateDistanceFilter(location.getSpeed());
                setPace(true);
            } else {
                if (isDebugging) {
                    startTone("beep");
                }
                return;
            }
        } else if (isMoving) {
            if (isDebugging) {
                startTone("beep");
            }
            // Only reset stationaryAlarm when accurate speed is detected, prevents spurious locations from resetting when stopped.
            if ((location.getSpeed() >= 1) && (location.getAccuracy() <= stationaryRadius)) {
                resetStationaryAlarm();
            }
            // Calculate latest distanceFilter, if it changed by 5 m/s, we'll reconfigure our pace.
            Integer newDistanceFilter = calculateDistanceFilter(location.getSpeed());
            if (newDistanceFilter != scaledDistanceFilter.intValue()) {
                Log.i(TAG,
                        "- updated distanceFilter, new: " + newDistanceFilter + ", old: " + scaledDistanceFilter);
                scaledDistanceFilter = newDistanceFilter;
                setPace(true);
            }
            if (location.distanceTo(lastLocation) < distanceFilter) {
                return;
            }
        } else if (stationaryLocation != null) {
            return;
        }
        // Go ahead and cache, push to server
        lastLocation = location;
        // persistLocation(location);
        broadcastLocation(location);

        // if (this.isNetworkConnected()) {
        //     Log.d(TAG, "Scheduling location network post");
        //     schedulePostLocations();            

        // } else {
        //     Log.d(TAG, "Network unavailable, waiting for now");
        // }
    }

From source file:com.vonglasow.michael.satstat.MapSectionFragment.java

/**
 * Updates the map view so that all markers are visible.
 *//*  w  ww  . j  ava2s.c  o m*/
public void updateMap() {
    boolean needsRedraw = false;
    Dimension dimension = mapMap.getModel().mapViewDimension.getDimension();
    // just trigger a redraw if we're not going to pan or zoom
    if ((dimension == null) || (!isMapViewAttached)) {
        mapMap.getLayerManager().redrawLayers();
        return;
    }
    // move locations into view and zoom out as needed
    int tileSize = mapMap.getModel().displayModel.getTileSize();
    BoundingBox bb = null;
    BoundingBox bb2 = null;
    for (Location l : providerLocations.values())
        if ((l != null) && (l.getProvider() != "")) {
            double lat = l.getLatitude();
            double lon = l.getLongitude();
            double yRadius = l.hasAccuracy() ? ((l.getAccuracy() * 360.0f) / EARTH_CIRCUMFERENCE) : 0;
            double xRadius = l.hasAccuracy() ? (yRadius * Math.abs(Math.cos(lat))) : 0;

            double minLon = Math.max(lon - xRadius, -180);
            double maxLon = Math.min(lon + xRadius, 180);
            double minLat = Math.max(lat - yRadius, -90);
            double maxLat = Math.min(lat + yRadius, 90);

            if (!isLocationStale(l)) {
                // location is up to date, add to main BoundingBox
                if (bb != null) {
                    minLat = Math.min(bb.minLatitude, minLat);
                    maxLat = Math.max(bb.maxLatitude, maxLat);
                    minLon = Math.min(bb.minLongitude, minLon);
                    maxLon = Math.max(bb.maxLongitude, maxLon);
                }
                bb = new BoundingBox(minLat, minLon, maxLat, maxLon);
            } else {
                // location is stale, add to stale BoundingBox
                if (bb2 != null) {
                    minLat = Math.min(bb2.minLatitude, minLat);
                    maxLat = Math.max(bb2.maxLatitude, maxLat);
                    minLon = Math.min(bb2.minLongitude, minLon);
                    maxLon = Math.max(bb2.maxLongitude, maxLon);
                }
                bb2 = new BoundingBox(minLat, minLon, maxLat, maxLon);
            }
        }
    if (bb == null)
        bb = bb2; // all locations are stale, center to them
    if (bb == null) {
        needsRedraw = true;
    } else {
        byte newZoom = LatLongUtils.zoomForBounds(dimension, bb, tileSize);
        if (newZoom < 0)
            newZoom = 0;
        if (newZoom < mapMap.getModel().mapViewPosition.getZoomLevel()) {
            mapMap.getModel().mapViewPosition.setZoomLevel(newZoom);
        } else {
            needsRedraw = true;
        }

        MapViewProjection proj = new MapViewProjection(mapMap);
        Point nw = proj.toPixels(new LatLong(bb.maxLatitude, bb.minLongitude));
        Point se = proj.toPixels(new LatLong(bb.minLatitude, bb.maxLongitude));

        // move only if bb is not entirely visible
        if ((nw.x < 0) || (nw.y < 0) || (se.x > dimension.width) || (se.y > dimension.height)) {
            mapMap.getModel().mapViewPosition.setCenter(bb.getCenterPoint());
        } else {
            needsRedraw = true;
        }
    }
    if (needsRedraw)
        mapMap.getLayerManager().redrawLayers();
}

From source file:org.rockettrack.MapFragment.java

@Override
protected void onRocketLocationChange() {
    if (mMap == null) {
        return;// w w w.ja v a2  s  .c  om
    }

    Location rocketLocation = getRocketLocation();

    if (rocketLocation == null)
        return;

    LatLng rocketPosition = new LatLng(rocketLocation.getLatitude(), rocketLocation.getLongitude());

    //Draw marker at Rocket position
    if (rocketMarker == null) {
        BitmapDescriptor rocketIcon = BitmapDescriptorFactory.fromResource(R.drawable.ic_rocket_map);
        rocketMarker = mMap
                .addMarker(new MarkerOptions().anchor(0.5f, 0.5f).position(rocketPosition).icon(rocketIcon));
    } else {
        rocketMarker.setPosition(rocketPosition);
    }
    if (rocketCircle == null) {
        CircleOptions options = new CircleOptions().center(rocketPosition).radius(rocketLocation.getAccuracy())
                .strokeColor(Color.RED).strokeWidth(1.0f).fillColor(Color.RED & 0x22FFFFFF);
        rocketCircle = mMap.addCircle(options);
    } else {
        rocketCircle.setCenter(rocketPosition);
        rocketCircle.setRadius(rocketLocation.getAccuracy());
    }

    updateBearing();

    List<Location> rocketLocationHistory = getRocketLocationHistory();
    if (rocketLocationHistory != null && rocketLocationHistory.size() > 0) {
        List<LatLng> rocketPosList = new ArrayList<LatLng>(rocketLocationHistory.size());
        for (Location l : rocketLocationHistory) {
            rocketPosList.add(new LatLng(l.getLatitude(), l.getLongitude()));
        }
        if (rocketPath == null) {
            rocketPath = mMap.addPolyline(new PolylineOptions().width(1.0f).color(Color.rgb(0, 0, 128)));
        }
        rocketPath.setPoints(rocketPosList);
    }

    //Draw line between myPosition and Rocket
    updateRocketLine(rocketLocation, rocketPosition);
}

From source file:com.marianhello.cordova.bgloc.LocationUpdateService.java

/**
     * Returns the most accurate and timely previously detected location.
     * Where the last result is beyond the specified maximum distance or
     * latency a one-off location update is returned via the {@link LocationListener}
     * specified in {@link setChangedLocationListener}.
     * @param minDistance Minimum distance before we require a location update.
     * @param minTime Minimum time required between location updates.
     * @return The most accurate and / or timely previously detected location.
     *//*ww  w.jav  a  2  s. c om*/
    public Location getLastBestLocation() {
        int minDistance = (int) stationaryRadius;
        long minTime = System.currentTimeMillis() - (locationTimeout * 1000);

        Log.i(TAG, "- fetching last best location " + minDistance + "," + minTime);
        Location bestResult = null;
        float bestAccuracy = Float.MAX_VALUE;
        long bestTime = Long.MIN_VALUE;

        // Iterate through all the providers on the system, keeping
        // note of the most accurate result within the acceptable time limit.
        // If no result is found within maxTime, return the newest Location.
        List<String> matchingProviders = locationManager.getAllProviders();
        for (String provider : matchingProviders) {
            Log.d(TAG, "- provider: " + provider);
            Location location = locationManager.getLastKnownLocation(provider);
            if (location != null) {
                Log.d(TAG, " location: " + location.getLatitude() + "," + location.getLongitude() + ","
                        + location.getAccuracy() + "," + location.getSpeed() + "m/s");
                float accuracy = location.getAccuracy();
                long time = location.getTime();
                Log.d(TAG, "time>minTime: " + (time > minTime) + ", accuracy<bestAccuracy: "
                        + (accuracy < bestAccuracy));
                if ((time > minTime && accuracy < bestAccuracy)) {
                    bestResult = location;
                    bestAccuracy = accuracy;
                    bestTime = time;
                }
            }
        }
        return bestResult;
    }