Java Code Examples for android.location.Location#getAccuracy()

The following examples show how to use android.location.Location#getAccuracy() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CircleUtil.java    From hellomap3d-android with MIT License 7 votes vote down vote up
/**
 * Calculates points for location circle, useful for "My Location" feature
 *
 * @param location from Android Location API
 * @param proj     map projection, usually EPSG3857
 * @return MapPosVector to construct Polygon object, and add it to DataSource and Layer
 */
public static MapPosVector createLocationCircle(Location location, Projection proj) {

    // number of points of circle
    int N = 50;
    int EARTH_RADIUS = 6378137;

    float radius = location.getAccuracy();
    double centerLat = location.getLatitude();
    double centerLon = location.getLongitude();

    MapPosVector points = new MapPosVector();
    for (int i = 0; i <= N; i++) {
        double angle = Math.PI * 2 * (i % N) / N;
        double dx = radius * Math.cos(angle);
        double dy = radius * Math.sin(angle);
        double lat = centerLat + (180 / Math.PI) * (dy / EARTH_RADIUS);
        double lon = centerLon + (180 / Math.PI) * (dx / EARTH_RADIUS) / Math.cos(centerLat * Math.PI / 180);
        points.add(proj.fromWgs84(new MapPos(lon, lat)));
    }
    return points;
}
 
Example 2
Source File: GeoUtils.java    From Walrus with GNU General Public License v3.0 6 votes vote down vote up
public static boolean isBetterLocation(Location location, Location currentBestLocation) {
    long timeDelta = location.getTime() - currentBestLocation.getTime();
    boolean isSignificantlyNewer = timeDelta > ONE_MINUTE;
    boolean isSignificantlyOlder = timeDelta < -ONE_MINUTE;
    boolean isNewer = timeDelta > 0;

    if (isSignificantlyNewer) {
        return true;
    } else if (isSignificantlyOlder) {
        return false;
    }

    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
    boolean isLessAccurate = accuracyDelta > 0;
    boolean isMoreAccurate = accuracyDelta < 0;
    boolean isSignificantlyLessAccurate = accuracyDelta > 200;

    boolean isFromSameProvider = isSameProvider(location.getProvider(),
            currentBestLocation.getProvider());

    return isMoreAccurate
            || (isNewer && !isLessAccurate)
            || (isNewer && !isSignificantlyLessAccurate && isFromSameProvider);
}
 
Example 3
Source File: Tracking.java    From Finder with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onLocationChanged(Location location) {
    if (location.hasAccuracy() && (location.getAccuracy() < accuracy)) {
        stop.removeCallbacks(stopper);
        locMan.removeUpdates(locListen);  //disable GPS listener after first accurate data
        String lat = String.format(Locale.US, "%.8f",location.getLatitude());
        String lon = String.format(Locale.US, "%.8f", location.getLongitude());
        String speed = String.format(Locale.US, "%.1f", location.getSpeed() * 3.6f);
        DateFormat df = new SimpleDateFormat("HH:mm");
        String date = df.format(Calendar.getInstance().getTime());
        append_send_coordinates(lat, lon, speed, date);
    } else {
        lastTrue = true;  //save not accurate data to sending, in case of big GPS work time
        lastLat = String.format(Locale.US, "%.8f",location.getLatitude());
        lastLon = String.format(Locale.US, "%.8f", location.getLongitude());
        lastSpeed = String.format(Locale.US, "%.1f", location.getSpeed() * 3.6f);  //default by function = 0 if not available
    }
}
 
Example 4
Source File: TwilightScanner.java    From PhoneProfilesPlus with Apache License 2.0 6 votes vote down vote up
private static boolean hasMoved(Location from, Location to) {
    if (to == null) {
        return false;
    }

    if (from == null) {
        return true;
    }

    // if new location is older than the current one, the device hasn't moved.
    if (to.getElapsedRealtimeNanos() < from.getElapsedRealtimeNanos()) {
        return false;
    }

    // Get the distance between the two points.
    float distance = from.distanceTo(to);

    // Get the total accuracy radius for both locations.
    float totalAccuracy = from.getAccuracy() + to.getAccuracy();

    // If the distance is greater than the combined accuracy of the two
    // points then they can't overlap and hence the user has moved.
    return distance >= totalAccuracy;
}
 
Example 5
Source File: HandlerService.java    From LibreTasks with Apache License 2.0 5 votes vote down vote up
/**
 * Insert GPS location data to the intent.
 * 
 * @param intent
 *          the intent to modify
 */
private void insertLocationData(Intent intent) {
  LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
  Location location = null;

  String bestProvider = locationManager.getBestProvider(new Criteria(), true);
  String locationData;
  try {
    location = locationManager.getLastKnownLocation(bestProvider);
    OmniArea newLocation = new OmniArea(null, location.getLatitude(), location.getLongitude(),
        location.getAccuracy());
    locationData = newLocation.toString();
  } catch (Exception e) {
    locationData = "";

    if (location == null) {
      /*
       * Use the normal logging since this case happens quite often, and we don't want to clutter
       * the logs.
       */
      Log.i(TAG, getString(R.string.location_not_available));
    } else if (bestProvider == null) {
      Logger.w(TAG, getString(R.string.location_no_provider));
    } else {
      Logger.w(TAG, getString(R.string.location_unknown_error), e);
    }
  }

  intent.putExtra(Event.ATTRIBUTE_LOCATION, locationData);
}
 
Example 6
Source File: Kalman.java    From DejaVu with GNU General Public License v3.0 5 votes vote down vote up
/**
 *
 * @param location
 */

public Kalman(Location location, double coordinateNoise) {
    final double accuracy = location.getAccuracy();
    final double coordinateNoiseDegrees = coordinateNoise * BackendService.METER_TO_DEG;
    double position, noise;
    long timeMs = location.getTime();

    // Latitude
    position = location.getLatitude();
    noise = accuracy * BackendService.METER_TO_DEG;
    mLatTracker = new Kalman1Dim(coordinateNoiseDegrees, timeMs);
    mLatTracker.setState(position, 0.0, noise);

    // Longitude
    position = location.getLongitude();
    noise = accuracy * Math.cos(Math.toRadians(location.getLatitude())) * BackendService.METER_TO_DEG;
    mLonTracker = new Kalman1Dim(coordinateNoiseDegrees, timeMs);
    mLonTracker.setState(position, 0.0, noise);

    // Altitude
    if (location.hasAltitude()) {
        position = location.getAltitude();
        noise = accuracy;
        mAltTracker = new Kalman1Dim(ALTITUDE_NOISE, timeMs);
        mAltTracker.setState(position, 0.0, noise);
    }
    mTimeOfUpdate = timeMs;
    samples = 1;
}
 
Example 7
Source File: LocationFudger.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Get the cached coarse location, or generate a new one and cache it.
 */
public Location getOrCreate(Location location) {
    synchronized (mLock) {
        Location coarse = location.getExtraLocation(Location.EXTRA_COARSE_LOCATION);
        if (coarse == null) {
            return addCoarseLocationExtraLocked(location);
        }
        if (coarse.getAccuracy() < mAccuracyInMeters) {
            return addCoarseLocationExtraLocked(location);
        }
        return coarse;
    }
}
 
Example 8
Source File: GeolocationHeader.java    From delion with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an X-Geo HTTP header string if:
 *  1. The current mode is not incognito.
 *  2. The url is a google search URL (e.g. www.google.co.uk/search?q=cars), and
 *  3. The user has not disabled sharing location with this url, and
 *  4. There is a valid and recent location available.
 *
 * Returns null otherwise.
 *
 * @param context The Context used to get the device location.
 * @param url The URL of the request with which this header will be sent.
 * @param isIncognito Whether the request will happen in an incognito tab.
 * @return The X-Geo header string or null.
 */
public static String getGeoHeader(Context context, String url, boolean isIncognito) {
    if (!isGeoHeaderEnabledForUrl(context, url, isIncognito, true)) {
        return null;
    }

    // Only send X-Geo header if there's a fresh location available.
    Location location = GeolocationTracker.getLastKnownLocation(context);
    if (location == null) {
        recordHistogram(UMA_LOCATION_NOT_AVAILABLE);
        return null;
    }
    if (GeolocationTracker.getLocationAge(location) > MAX_LOCATION_AGE) {
        recordHistogram(UMA_LOCATION_STALE);
        return null;
    }

    recordHistogram(UMA_HEADER_SENT);

    // Timestamp in microseconds since the UNIX epoch.
    long timestamp = location.getTime() * 1000;
    // Latitude times 1e7.
    int latitude = (int) (location.getLatitude() * 10000000);
    // Longitude times 1e7.
    int longitude = (int) (location.getLongitude() * 10000000);
    // Radius of 68% accuracy in mm.
    int radius = (int) (location.getAccuracy() * 1000);

    // Encode location using ascii protobuf format followed by base64 encoding.
    // https://goto.google.com/partner_location_proto
    String locationAscii = String.format(Locale.US,
            "role:1 producer:12 timestamp:%d latlng{latitude_e7:%d longitude_e7:%d} radius:%d",
            timestamp, latitude, longitude, radius);
    String locationBase64 = new String(Base64.encode(locationAscii.getBytes(), Base64.NO_WRAP));

    return "X-Geo: a " + locationBase64;
}
 
Example 9
Source File: LocationHelper.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
public static boolean isBetterLocation(final Location location, final Location prevLoc) {
    if (prevLoc == null) {
        return true;
    }

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

    if (isSignificantlyNewer) {
        return true;
    } else if (isSignificantlyOlder) {
        return false;
    }

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

    // Check if the old and new location are from the same provider
    final boolean isFromSameProvider = isSameProvider(location.getProvider(), prevLoc.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;
}
 
Example 10
Source File: GeoPointMapActivity.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onLocationChanged(Location location) {
    if (!inViewMode && !isManualSelectedLocation) {
        if (location != null &&
                (this.location == null || (location.getAccuracy() < this.location.getAccuracy()))) {
            this.location = location;
            drawMarker();
        }
    }
}
 
Example 11
Source File: BackgroundService.java    From BackPackTrackII with GNU General Public License v3.0 4 votes vote down vote up
private void handlePassiveLocationUpdate(Intent intent) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Process passive location update
    Location location = (Location) intent.getExtras().get(LocationManager.KEY_LOCATION_CHANGED);
    Log.i(TAG, "Update passive location=" + location);
    if (location == null || (location.getLatitude() == 0.0 && location.getLongitude() == 0.0))
        return;

    // Filter inaccurate passive locations
    int pref_inaccurate = Integer.parseInt(prefs.getString(SettingsFragment.PREF_PASSIVE_INACCURATE, SettingsFragment.DEFAULT_PASSIVE_INACCURATE));
    if (!location.hasAccuracy() || location.getAccuracy() > pref_inaccurate) {
        Log.i(TAG, "Filtering inaccurate passive location=" + location);
        return;
    }

    // Get last location
    Location lastLocation = LocationDeserializer.deserialize(prefs.getString(SettingsFragment.PREF_LAST_LOCATION, null));
    if (lastLocation == null) {
        Log.i(TAG, "Passive location without last location, location=" + location);
        return;
    }

    // Filter old locations
    if (location.getTime() <= lastLocation.getTime()) {
        Log.i(TAG, "Passive location is older than last location, location=" + location);
        return;
    }

    // Correct altitude
    correctAltitude(location, this);

    // Filter nearby passive locations
    int pref_nearby = Integer.parseInt(prefs.getString(SettingsFragment.PREF_PASSIVE_NEARBY, SettingsFragment.DEFAULT_PASSIVE_NEARBY));
    if (Util.distance(lastLocation, location) < pref_nearby &&
            (lastLocation.hasAccuracy() ? lastLocation.getAccuracy() : Float.MAX_VALUE) <=
                    (location.hasAccuracy() ? location.getAccuracy() : Float.MAX_VALUE)) {
        Log.i(TAG, "Filtering nearby passive location=" + location);
        return;
    }

    float bchange = 0;
    double achange = 0;
    boolean update = false;

    // Handle bearing change
    if (location.hasBearing()) {
        int pref_bearing_change = Integer.parseInt(prefs.getString(SettingsFragment.PREF_PASSIVE_BEARING, SettingsFragment.DEFAULT_PASSIVE_BEARING));
        bchange = Math.abs(lastLocation.getBearing() - location.getBearing());
        if (bchange > 180)
            bchange = 360 - bchange;
        if (!lastLocation.hasBearing() || bchange > pref_bearing_change) {
            Log.i(TAG, "Bearing changed to " + location.getBearing());
            update = true;
        }
    }

    // Handle altitude change
    if (location.hasAltitude()) {
        int pref_altitude_change = Integer.parseInt(prefs.getString(SettingsFragment.PREF_PASSIVE_ALTITUDE, SettingsFragment.DEFAULT_PASSIVE_ALTITUDE));
        achange = Math.abs(lastLocation.getAltitude() - location.getAltitude());
        if (!lastLocation.hasAltitude() || achange > pref_altitude_change) {
            Log.i(TAG, "Altitude changed to " + location.getAltitude());
            update = true;
        }
    }

    if (update) {
        // Persist new location
        prefs.edit().putString(SettingsFragment.PREF_LAST_LOCATION, LocationSerializer.serialize(location)).apply();
        DatabaseHelper dh = null;
        try {
            dh = new DatabaseHelper(this);
            int altitude_type = (location.hasAltitude() ? ALTITUDE_GPS : ALTITUDE_NONE);
            dh.insertLocation(location, altitude_type, null).close();
        } finally {
            if (dh != null)
                dh.close();
        }

        // Feedback
        showStateNotification(this);
        if (Util.debugMode(this))
            Util.toast(getString(R.string.title_trackpoint) +
                    " " + getProviderName(location, this) +
                    " " + Math.round(bchange) +
                    "° / " + Math.round(achange) + "m", Toast.LENGTH_SHORT, this);
    }
}
 
Example 12
Source File: LocationUtils.java    From Android-UtilCode with Apache License 2.0 4 votes vote down vote up
/**
 * 是否更好的位置
 *
 * @param newLocation         The new Location that you want to evaluate
 * @param currentBestLocation The current Location fix, to which you want to compare the new one
 * @return {@code true}: 是<br>{@code false}: 否
 */
public static boolean isBetterLocation(Location newLocation, 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 = newLocation.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) (newLocation.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(newLocation.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;
}
 
Example 13
Source File: LocationMonitor.java    From ploggy with GNU General Public License v3.0 4 votes vote down vote up
private boolean isBetterLocation(Location location, Location currentBestLocation) {

        final int TWO_MINUTES = 1000 * 60 * 2;

        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;
    }
 
Example 14
Source File: DeviceLocation.java    From ARCore-Location with MIT License 4 votes vote down vote up
private boolean filterAndAddLocation(Location location) {

        if (currentBestLocation == null) {
            currentBestLocation = location;

            locationEvents();
        }

        long age = getLocationAge(location);

        if (age > 5 * 1000) { //more than 5 seconds
            Log.d(TAG, "Location is old");
            oldLocationList.add(location);

            if (locationScene.isDebugEnabled())
                Toast.makeText(context, "Rejected: old", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (location.getAccuracy() <= 0) {
            Log.d(TAG, "Latitidue and longitude values are invalid.");
            if (locationScene.isDebugEnabled())
                Toast.makeText(context, "Rejected: invalid", Toast.LENGTH_SHORT).show();
            noAccuracyLocationList.add(location);
            return false;
        }

        //setAccuracy(newLocation.getAccuracy());
        float horizontalAccuracy = location.getAccuracy();
        if (horizontalAccuracy > getMinimumAccuracy()) { //10meter filter
            Log.d(TAG, "Accuracy is too low.");
            inaccurateLocationList.add(location);
            if (locationScene.isDebugEnabled())
                Toast.makeText(context, "Rejected: innacurate", Toast.LENGTH_SHORT).show();
            return false;
        }


        /* Kalman Filter */
        float Qvalue;

        long locationTimeInMillis = (long) (location.getElapsedRealtimeNanos() / 1000000);
        long elapsedTimeInMillis = locationTimeInMillis - runStartTimeInMillis;

        if (currentSpeed == 0.0f) {
            Qvalue = 3.0f; //3 meters per second
        } else {
            Qvalue = currentSpeed; // meters per second
        }

        kalmanFilter.Process(location.getLatitude(), location.getLongitude(), location.getAccuracy(), elapsedTimeInMillis, Qvalue);
        double predictedLat = kalmanFilter.get_lat();
        double predictedLng = kalmanFilter.get_lng();

        Location predictedLocation = new Location("");//provider name is unecessary
        predictedLocation.setLatitude(predictedLat);//your coords of course
        predictedLocation.setLongitude(predictedLng);
        float predictedDeltaInMeters = predictedLocation.distanceTo(location);

        if (predictedDeltaInMeters > 60) {
            Log.d(TAG, "Kalman Filter detects mal GPS, we should probably remove this from track");
            kalmanFilter.consecutiveRejectCount += 1;

            if (kalmanFilter.consecutiveRejectCount > 3) {
                kalmanFilter = new KalmanLatLong(3); //reset Kalman Filter if it rejects more than 3 times in raw.
            }

            kalmanNGLocationList.add(location);
            if (locationScene.isDebugEnabled())
                Toast.makeText(context, "Rejected: kalman filter", Toast.LENGTH_SHORT).show();
            return false;
        } else {
            kalmanFilter.consecutiveRejectCount = 0;
        }


        Log.d(TAG, "Location quality is good enough.");
        currentBestLocation = predictedLocation;
        currentSpeed = location.getSpeed();
        locationList.add(location);

        locationEvents();


        return true;
    }
 
Example 15
Source File: BarometerNetworkActivity.java    From PressureNet with GNU General Public License v3.0 4 votes vote down vote up
/** Determines whether one Location reading is better than the current Location fix
 * @param location  The new Location that you want to evaluate
 */
protected boolean isBetterLocation(Location location) {
	if (bestLocation == null) {
		// A new location is always better than no location
		log("new location is always better than no location");
		return true;
	}

	// Check whether the new location fix is newer or older
	long timeDelta = location.getTime() - bestLocation.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) {
		log("new location is significantly newer");
		return true;
		// If the new location is more than two minutes older, it must be worse
	} else if (isSignificantlyOlder) {
		log("new location is significantly older");
		return false;
	}


	// Check whether the new location fix is more or less accurate
	int accuracyDelta = (int) (location.getAccuracy() - bestLocation.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(),
			bestLocation.getProvider());



	// Determine location quality using a combination of timeliness, accuracy, and completeness (altitude)
	if (isMoreAccurate && isNewer) {
		return true;
	} else if (isNewer && !isLessAccurate) {
		return true;
	} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
		return true;
	}
	return false;
}
 
Example 16
Source File: DistanceFilterLocationProvider.java    From background-geolocation-android with Apache License 2.0 4 votes vote down vote up
public void onLocationChanged(Location location) {
    logger.debug("Location change: {} isMoving={}", location.toString(), isMoving);

    if (!isMoving && !isAcquiringStationaryLocation && stationaryLocation==null) {
        // Perhaps our GPS signal was interupted, re-acquire a stationaryLocation now.
        setPace(false);
    }

    showDebugToast( "mv:" + isMoving + ",acy:" + location.getAccuracy() + ",v:" + location.getSpeed() + ",df:" + scaledDistanceFilter);

    if (isAcquiringStationaryLocation) {
        if (stationaryLocation == null || stationaryLocation.getAccuracy() > location.getAccuracy()) {
            stationaryLocation = location;
        }
        if (++locationAcquisitionAttempts == MAX_STATIONARY_ACQUISITION_ATTEMPTS) {
            isAcquiringStationaryLocation = false;
            startMonitoringStationaryRegion(stationaryLocation);
            handleStationary(stationaryLocation, stationaryRadius);
            return;
        } else {
            // Unacceptable stationary-location: bail-out and wait for another.
            playDebugTone(Tone.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.
            playDebugTone(Tone.DOODLY_DOO);
            isAcquiringSpeed = false;
            scaledDistanceFilter = calculateDistanceFilter(location.getSpeed());
            setPace(true);
        } else {
            playDebugTone(Tone.BEEP);
            return;
        }
    } else if (isMoving) {
        playDebugTone(Tone.BEEP);

        // Only reset stationaryAlarm when accurate speed is detected, prevents spurious locations from resetting when stopped.
        if ( (location.getSpeed() >= 1) && (location.getAccuracy() <= mConfig.getStationaryRadius()) ) {
            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()) {
            logger.info("Updating distanceFilter: new={} old={}", newDistanceFilter, scaledDistanceFilter);
            scaledDistanceFilter = newDistanceFilter;
            setPace(true);
        }
        if (lastLocation != null && location.distanceTo(lastLocation) < mConfig.getDistanceFilter()) {
            return;
        }
    } else if (stationaryLocation != null) {
        return;
    }
    // Go ahead and cache, push to server
    lastLocation = location;
    handleLocation(location);
}
 
Example 17
Source File: LocationValidator.java    From TowerCollector with Mozilla Public License 2.0 4 votes vote down vote up
public boolean hasRequiredAccuracy(Location location) {
    return (location.hasAccuracy() && location.getAccuracy() <= minAccuracy);
}
 
Example 18
Source File: TelephonyHelper.java    From Local-GSM-Backend with Apache License 2.0 4 votes vote down vote up
public Location weightedAverage(String source, Collection<Location> locations) {
        Location rslt;

        if (locations == null || locations.size() == 0) {
            return null;
        }

        int num = locations.size();
        int totalWeight = 0;
        double latitude = 0;
        double longitude = 0;
        float accuracy = 0;
        int altitudes = 0;
        double altitude = 0;

        for (Location value : locations) {
            if (value != null) {
                // Create weight value based on accuracy. Higher accuracy
                // (lower tower radius/range) towers get higher weight.
                float thisAcc = value.getAccuracy();
                if (thisAcc < 1f)
                    thisAcc = 1f;

                int wgt = (int) (100000f / thisAcc);
                if (wgt < 1)
                    wgt = 1;

                latitude += (value.getLatitude() * wgt);
                longitude += (value.getLongitude() * wgt);
                accuracy += (value.getAccuracy() * wgt);
                totalWeight += wgt;

//                if (DEBUG) Log.i(TAG, "(lat="+ latitude + ", lng=" + longitude + ", acc=" + accuracy + ") / wgt=" + totalWeight );

                if (value.hasAltitude()) {
                    altitude += value.getAltitude();
                    altitudes++;
                }
            }
        }
        latitude = latitude / totalWeight;
        longitude = longitude / totalWeight;
        accuracy = accuracy / totalWeight;
        altitude = altitude / altitudes;
        Bundle extras = new Bundle();
        extras.putInt("AVERAGED_OF", num);
//        if (DEBUG) Log.i(TAG, "Location est (lat="+ latitude + ", lng=" + longitude + ", acc=" + accuracy);

        if (altitudes > 0) {
            rslt = LocationHelper.create(source,
                    latitude,
                    longitude,
                    altitude,
                    accuracy,
                    extras);
        } else {
            rslt = LocationHelper.create(source,
                    latitude,
                    longitude,
                    accuracy,
                    extras);
        }
        rslt.setTime(System.currentTimeMillis());
        return rslt;
    }
 
Example 19
Source File: BackgroundService.java    From BackPackTrackII with GNU General Public License v3.0 4 votes vote down vote up
private void handleLocationUpdate(Intent intent) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Process location update
    int locationType = prefs.getInt(SettingsFragment.PREF_LOCATION_TYPE, -1);
    Location location = (Location) intent.getExtras().get(LocationManager.KEY_LOCATION_CHANGED);
    Log.i(TAG, "Update location=" + location + " type=" + locationType);
    if (location == null || (location.getLatitude() == 0.0 && location.getLongitude() == 0.0))
        return;

    // Check if still acquiring location
    if (prefs.getInt(SettingsFragment.PREF_STATE, STATE_IDLE) == STATE_IDLE) {
        Log.i(TAG, "Not acquiring anymore");
        return;
    }

    // Filter inaccurate location
    int pref_inaccurate = Integer.parseInt(prefs.getString(SettingsFragment.PREF_INACCURATE, SettingsFragment.DEFAULT_INACCURATE));
    if (!location.hasAccuracy() || location.getAccuracy() > pref_inaccurate) {
        Log.i(TAG, "Filtering inaccurate location=" + location);
        return;
    }

    // Filter old locations
    Location lastLocation = LocationDeserializer.deserialize(prefs.getString(SettingsFragment.PREF_LAST_LOCATION, null));
    if (lastLocation != null && location.getTime() <= lastLocation.getTime()) {
        Log.i(TAG, "Location is older than last location, location=" + location);
        return;
    }

    // Correct altitude
    correctAltitude(location, this);

    // Persist better location
    Location bestLocation = LocationDeserializer.deserialize(prefs.getString(SettingsFragment.PREF_BEST_LOCATION, null));
    if (isBetterLocation(bestLocation, location)) {
        Log.i(TAG, "Better location=" + location);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt(SettingsFragment.PREF_STATE, STATE_ACQUIRED);
        editor.putString(SettingsFragment.PREF_BEST_LOCATION, LocationSerializer.serialize(location));
        editor.apply();
        showStateNotification(this);
    }

    // Check altitude
    boolean pref_altitude = prefs.getBoolean(SettingsFragment.PREF_ALTITUDE, SettingsFragment.DEFAULT_ALTITUDE);
    if (!location.hasAltitude() && pref_altitude) {
        Log.i(TAG, "No altitude, but preferred, location=" + location);
        return;
    }

    // Check accuracy
    int pref_accuracy;
    if (locationType == LOCATION_WAYPOINT)
        pref_accuracy = Integer.parseInt(prefs.getString(SettingsFragment.PREF_WP_ACCURACY, SettingsFragment.DEFAULT_WP_ACCURACY));
    else
        pref_accuracy = Integer.parseInt(prefs.getString(SettingsFragment.PREF_TP_ACCURACY, SettingsFragment.DEFAULT_TP_ACCURACY));
    if (!location.hasAccuracy() || location.getAccuracy() > pref_accuracy) {
        Log.i(TAG, "Accuracy not reached, location=" + location);
        return;
    }

    // Check pressure
    boolean pressure_enabled = prefs.getBoolean(SettingsFragment.PREF_PRESSURE_ENABLED, SettingsFragment.DEFAULT_PRESSURE_ENABLED);
    if (pressure_enabled)
        if (prefs.getFloat(SettingsFragment.PREF_PRESSURE_VALUE, -1) < 0) {
            Log.i(TAG, "Pressure not available yet");
            return;
        }

    stopLocating(this);

    // Process location
    handleLocation(locationType, location);
}
 
Example 20
Source File: LocationUtil.java    From open-location-code with Apache License 2.0 4 votes vote down vote up
/**
 * Determines whether one Location reading is better than the current Location fix.
 * Copied from 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;
}