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:br.com.rescue_bots_android.bluetooth.MainActivity.java

@Override
public void notifyLocation(Location location) {
    if (joystickEnabled) { //modo joystick habilitado
        return;//  w  w  w .  j a v  a2  s  .  co m
    }
    if (vunforiaMode) {
        return;
    }
    if (location.getAccuracy() >= accuraccy) {

        mTxtReceive.append(location.getAccuracy() + " -> accuracy is menor than -> " + accuraccy);
        return;
    } else {
        mTxtReceive.append("Accuracy -> " + location.getAccuracy());
        //accuraccy = location.getAccuracy();
        /*if(!isBetterLocation(origin, location)){
           mTxtReceive.append("Not is better -> " +location.getAccuracy());
           return;
        }*/
    }

    String locationText = getLocationText(gps.getLocation());
    //if(gps.getLocation()!=null){
    //    trackerController.inserir(fillLocationBean(location));
    //}
    if (locationText != null) {
        Log.i("INFO", locationText);
    } else {
        Log.i("INFO", "Sem coordenada");
    }
    //SharedPreferences settings = this.getSharedPreferences(ConfigActivity.PREFS_NAME, 0);
    //String serverIP = settings.getString(ConfigActivity.PARAM_SERVERIP , "");
    //String serverPort = settings.getString(ConfigActivity.PARAM_SERVERPORT , "");

    StringBuilder message = new StringBuilder();
    message.append(locationText);
    /*if(isFinishing()){
       message.append("YES;"); //ok i get
    }else{
       message.append("NO;"); //found
    }*/
    //if(origin==null){
    origin = new Location(gps.getLocation());
    //}

    geoField = new GeomagneticField(Double.valueOf(location.getLatitude()).floatValue(),
            Double.valueOf(location.getLongitude()).floatValue(),
            Double.valueOf(location.getAltitude()).floatValue(), System.currentTimeMillis());

    myBearing += geoField.getDeclination();
    heading = myBearing - (myBearing + heading);
    gpsDirection = Math.round(-heading / 360 + 180);

    if (origin != null && destiny != null) {
        //Location dest = new Location("dest");
        //dest.setLatitude(destiny[0]);
        //dest.setLongitude(destiny[1]);
        distance = meterDistanceBetweenPoints(origin.getLatitude(), origin.getLongitude(), destiny[0],
                destiny[1]);
    } else {
        distance = -1;
    }
    if (distance > 1) { //distancia in mater around
        message.append("NO"); //found
    } else {
        if (distance >= 0 && distance <= 1) {
            message.append("YES"); //ok i get
            destiny = null;
            sendSerial("g");
        } else {
            message.append("NO"); //found
        }

    }
    SharedPreferences settings = this.getSharedPreferences(ConfigActivity.PREFS_NAME, 0);
    String serverIP = settings.getString(ConfigActivity.PARAM_SERVERIP, "");
    String serverPort = settings.getString(ConfigActivity.PARAM_SERVERPORT, "");

    String robotId = settings.getString(ConfigActivity.PARAM_ROBOTID, "");
    robottype = settings.getString(ConfigActivity.PARAM_BOTTYPE, "");
    message.append(";" + robottype);
    message.append(";" + robotId); //found

    message.append(";" + currentDegree);
    message.append(";" + gpsDirection);
    message.append(";" + distance);
    message.append(";" + diference);
    message.append(";" + index);
    message.append(";" + lastmessage);
    message.append(";" + foundsucess);

    if (sendToServer(serverIP, serverPort, message, robotId)) {
        message.append("RESCUEBOT CLIENT at " + serverIP + ":" + serverPort + "ONLINE =)");
    } else {
        message.append(
                "<font color=red>RESCUEBOT CLIENT at " + serverIP + ":" + serverPort + "OFFLINE =(</font>");
    }
}

From source file:obdii.starter.automotive.iot.ibm.com.iot4a_obdii.Home.java

private boolean setLocationInformation() {
    // returns false if GPS and Network settings are needed
    final ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
            Context.CONNECTIVITY_SERVICE);
    final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
            && (networkInfo != null && networkInfo.isConnected())) {
        if (ActivityCompat.checkSelfPermission(getApplicationContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(getApplicationContext(),
                        Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return true;
        }// www . jav a  2s.co m

        locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);

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

        for (String provider : providers) {
            if (ActivityCompat.checkSelfPermission(getApplicationContext(),
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(getApplicationContext(),
                            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return true;
            }

            final Location lastKnown = locationManager.getLastKnownLocation(provider);

            if (lastKnown == null) {
                continue;
            }
            if (finalLocation == null || (lastKnown.getAccuracy() < finalLocation.getAccuracy())) {
                finalLocation = lastKnown;
            }
        }

        if (finalLocation == null) {
            Log.e("Location Data", "Not Working!");
        } else {
            Log.d("Location Data", finalLocation.getLatitude() + " " + finalLocation.getLongitude() + "");
            location = finalLocation;
        }

        return true;
    } else {
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Toast.makeText(getApplicationContext(), "Please turn on your GPS", Toast.LENGTH_LONG).show();

            final Intent gpsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(gpsIntent, GPS_INTENT);

            if (networkInfo == null) {
                networkIntentNeeded = true;
            }
            return false;
        } else {
            if (networkInfo == null) {
                Toast.makeText(getApplicationContext(), "Please turn on Mobile Data or WIFI", Toast.LENGTH_LONG)
                        .show();

                final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
                startActivityForResult(settingsIntent, SETTINGS_INTENT);
                return false;
            } else {
                return true;
            }
        }
    }
}

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

private boolean postLocation(com.marianhello.cordova.bgloc.data.Location l, LocationDAO dao) {
        if (l == null) {
            Log.w(TAG, "postLocation: null location");
            return false;
        }//from  w  w  w . j  av  a  2 s  .  co  m
        try {
            lastUpdateTime = SystemClock.elapsedRealtime();
            Log.i(TAG, "Posting  native location update: " + l);
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost request = new HttpPost(url);

            JSONObject location = new JSONObject();
            location.put("latitude", l.getLatitude());
            location.put("longitude", l.getLongitude());
            location.put("accuracy", l.getAccuracy());
            location.put("speed", l.getSpeed());
            location.put("bearing", l.getBearing());
            location.put("altitude", l.getAltitude());
            location.put("recorded_at", dao.dateToString(l.getRecordedAt()));
            params.put("location", location);

            Log.i(TAG, "location: " + location.toString());

            StringEntity se = new StringEntity(params.toString());
            request.setEntity(se);
            request.setHeader("Accept", "application/json");
            request.setHeader("Content-type", "application/json");

            Iterator<String> headkeys = headers.keys();
            while (headkeys.hasNext()) {
                String headkey = headkeys.next();
                if (headkey != null) {
                    Log.d(TAG, "Adding Header: " + headkey + " : " + (String) headers.getString(headkey));
                    request.setHeader(headkey, (String) headers.getString(headkey));
                }
            }
            Log.d(TAG, "Posting to " + request.getURI().toString());
            HttpResponse response = httpClient.execute(request);
            Log.i(TAG, "Response received: " + response.getStatusLine());
            if (response.getStatusLine().getStatusCode() == 200) {
                return true;
            } else {
                return false;
            }
        } catch (Throwable e) {
            Log.w(TAG, "Exception posting location: " + e);
            e.printStackTrace();
            return false;
        }
    }

From source file:org.nasa.openspace.gc.geolocation.LocationActivity.java

/** Determines whether one Location reading is better than the current Location fix.
  * Code taken from//from   www .ja v a  2  s . c  o m
  * http://developer.android.com/guide/topics/location/obtaining-user-location.html
  *
  * @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 The better Location object based on recency and accuracy.
  */
protected Location getBetterLocation(Location newLocation, Location currentBestLocation) {
    if (currentBestLocation == null) {
        // A new location is always better than no location
        return newLocation;
    }

    // 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 newLocation;
        // If the new location is more than two minutes older, it must be worse
    } else if (isSignificantlyOlder) {
        return currentBestLocation;
    }

    // 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 newLocation;
    } else if (isNewer && !isLessAccurate) {
        return newLocation;
    } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
        return newLocation;
    }
    return currentBestLocation;
}

From source file:at.alladin.rmbt.android.util.InformationCollector.java

public Location getLocationInfo() {
    if (enableGeoLocation) {
        if (locationManager == null) {
            // init location Manager
            locationManager = new InfoGeoLocation(context);
            locationManager.start();/*  ww w  . j av  a  2s  .c  om*/
        }
        final Location curLocation = locationManager.getLastKnownLocation();

        if (curLocation != null && this.collectInformation) {
            geoLocations.add(new GeoLocationItem(curLocation.getTime(), curLocation.getLatitude(),
                    curLocation.getLongitude(), curLocation.getAccuracy(), curLocation.getAltitude(),
                    curLocation.getBearing(), curLocation.getSpeed(), curLocation.getProvider()));
            Log.i(DEBUG_TAG, "Location: " + curLocation.toString());
        }

        return curLocation;
    } else {
        return null;
    }

}

From source file:com.wiret.arbrowser.AbstractArchitectCamActivity.java

private void initArView() {
    /* set AR-view for life-cycle notifications etc. */
    this.architectView = (ArchitectView) this.findViewById(this.getArchitectViewId());

    /* pass SDK key if you have one, this one is only valid for this package identifier and must not be used somewhere else */
    final StartupConfiguration config = new StartupConfiguration(this.getWikitudeSDKLicenseKey(),
            this.getFeatures(), this.getCameraPosition());

    /* first mandatory life-cycle notification */
    this.architectView.onCreate(config);

    // set accuracy listener if implemented, you may e.g. show calibration prompt for compass using this listener
    this.sensorAccuracyListener = this.getSensorAccuracyListener();

    // set urlListener, any calls made in JS like "document.location = 'architectsdk://foo?bar=123'" is forwarded to this listener, use this to interact between JS and native Android activity/fragment
    this.urlListener = this.getUrlListener();

    // register valid urlListener in architectView, ensure this is set before content is loaded to not miss any event
    if (this.urlListener != null && this.architectView != null) {
        this.architectView.registerUrlListener(this.getUrlListener());
    }// www .  j a  v  a2 s.  co  m

    if (hasGeo()) {
        // listener passed over to locationProvider, any location update is handled here
        this.locationListener = new LocationListener() {

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            @Override
            public void onProviderEnabled(String provider) {
            }

            @Override
            public void onProviderDisabled(String provider) {
            }

            @Override
            public void onLocationChanged(final Location location) {
                // forward location updates fired by LocationProvider to architectView, you can set lat/lon from any location-strategy
                if (location != null) {
                    // sore last location as member, in case it is needed somewhere (in e.g. your adjusted project)
                    AbstractArchitectCamActivity.this.lastKnownLocaton = location;
                    if (AbstractArchitectCamActivity.this.architectView != null) {
                        // check if location has altitude at certain accuracy level & call right architect method (the one with altitude information)
                        if (location.hasAltitude() && location.hasAccuracy() && location.getAccuracy() < 7) {
                            AbstractArchitectCamActivity.this.architectView.setLocation(location.getLatitude(),
                                    location.getLongitude(), location.getAltitude(), location.getAccuracy());
                        } else {
                            AbstractArchitectCamActivity.this.architectView.setLocation(location.getLatitude(),
                                    location.getLongitude(),
                                    location.hasAccuracy() ? location.getAccuracy() : 1000);
                        }
                    }
                }
            }
        };

        // locationProvider used to fetch user position
        this.locationProvider = getLocationProvider(this.locationListener);
    } else {
        this.locationProvider = null;
        this.locationListener = null;
    }
}

From source file:com.wipro.sa349342.wmar.AbstractArchitectCamActivity.java

/** Called when the activity is first created. */
@SuppressLint("NewApi")
@Override// ww w .  j a  va 2  s  .c om
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /* pressing volume up/down should cause music volume changes */
    this.setVolumeControlStream(AudioManager.STREAM_MUSIC);

    /* set samples content view */
    this.setContentView(this.getContentViewId());

    this.setTitle(this.getActivityTitle());

    View mapFrag = findViewById(R.id.map);

    if (this.isMapPanelRequired()) {

        mapFrag.setVisibility(View.VISIBLE);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(map);

        mapFragment.getMapAsync(AbstractArchitectCamActivity.this);
    } else {
        mapFrag.setVisibility(View.GONE);
    }

    /*
     *   this enables remote debugging of a WebView on Android 4.4+ when debugging = true in AndroidManifest.xml
     *   If you get a compile time error here, ensure to have SDK 19+ used in your ADT/Eclipse.
     *   You may even delete this block in case you don't need remote debugging or don't have an Android 4.4+ device in place.
     *   Details: https://developers.google.com/chrome-developer-tools/docs/remote-debugging
     */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        if (0 != (getApplicationInfo().flags &= ApplicationInfo.FLAG_DEBUGGABLE)) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
    }

    /* set AR-view for life-cycle notifications etc. */

    this.architectView = (ArchitectView) this.findViewById(this.getArchitectViewId());

    /* pass SDK key if you have one, this one is only valid for this package identifier and must not be used somewhere else */
    final StartupConfiguration config = new StartupConfiguration(this.getWikitudeSDKLicenseKey(),
            this.getFeatures(), this.getCameraPosition());

    try {
        /* first mandatory life-cycle notification */
        this.architectView.onCreate(config);
    } catch (RuntimeException rex) {
        this.architectView = null;
        Toast.makeText(getApplicationContext(), "can't create Architect View", Toast.LENGTH_SHORT).show();
        Log.e(this.getClass().getName(), "Exception in ArchitectView.onCreate()", rex);
    }

    // set accuracy listener if implemented, you may e.g. show calibration prompt for compass using this listener
    this.sensorAccuracyListener = this.getSensorAccuracyListener();

    // set urlListener, any calls made in JS like "document.location = 'architectsdk://foo?bar=123'" is forwarded to this listener, use this to interact between JS and native Android activity/fragment
    this.urlListener = this.getUrlListener();

    // register valid urlListener in architectView, ensure this is set before content is loaded to not miss any event
    if (this.urlListener != null && this.architectView != null) {
        this.architectView.registerUrlListener(this.getUrlListener());
    }

    if (hasGeo()) {
        // listener passed over to locationProvider, any location update is handled here
        this.locationListener = new LocationListener() {

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            @Override
            public void onProviderEnabled(String provider) {
            }

            @Override
            public void onProviderDisabled(String provider) {
            }

            @Override
            public void onLocationChanged(final Location location) {
                // forward location updates fired by LocationProvider to architectView, you can set lat/lon from any location-strategy
                if (location != null) {
                    // sore last location as member, in case it is needed somewhere (in e.g. your adjusted project)
                    AbstractArchitectCamActivity.this.lastKnownLocaton = location;
                    if (AbstractArchitectCamActivity.this.architectView != null) {
                        // check if location has altitude at certain accuracy level & call right architect method (the one with altitude information)
                        if (location.hasAltitude() && location.hasAccuracy() && location.getAccuracy() < 7) {
                            AbstractArchitectCamActivity.this.architectView.setLocation(location.getLatitude(),
                                    location.getLongitude(), location.getAltitude(), location.getAccuracy());
                        } else {
                            AbstractArchitectCamActivity.this.architectView.setLocation(location.getLatitude(),
                                    location.getLongitude(),
                                    location.hasAccuracy() ? location.getAccuracy() : 1000);
                        }
                    }

                    // currentLocationMarker(location);
                }
            }
        };

        // locationProvider used to fetch user position
        this.locationProvider = getLocationProvider(this.locationListener);

    } else {
        this.locationProvider = null;
        this.locationListener = null;
    }
}

From source file:org.spontaneous.trackservice.RemoteService.java

/**
 * Some GPS waypoints received are of to low a quality for tracking use. Here we filter those out.
 *
 * @param proposedLocation/*from  w w w  .  j av a  2s  .com*/
 * @return either the (cleaned) original or null when unacceptable
 */
// TODO: Diese Methode auslagern und auch in StartFragment verwenden
public Location locationFilter(Location proposedLocation) {

    // Do no include log wrong 0.0 lat 0.0 long, skip to next value in while-loop
    if (proposedLocation != null
            && (proposedLocation.getLatitude() == 0.0d || proposedLocation.getLongitude() == 0.0d)) {
        Log.w(TAG, "A wrong location was received, 0.0 latitude and 0.0 longitude... ");
        proposedLocation = null;
    }

    // Do not log a waypoint which is more inaccurate then is configured to be acceptable
    if (proposedLocation != null && proposedLocation.getAccuracy() > this.mMaxAcceptableAccuracy) {
        Log.w(TAG, String.format("A weak location was received, lots of inaccuracy... (%f is more then max %f)",
                proposedLocation.getAccuracy(), this.mMaxAcceptableAccuracy));
        proposedLocation = addBadLocation(proposedLocation);
    }

    // Do not log a waypoint which might be on any side of the previous waypoint
    if (proposedLocation != null && this.mPreviousLocation != null
            && proposedLocation.getAccuracy() > this.mPreviousLocation.distanceTo(proposedLocation)) {
        Log.w(TAG, String.format(
                "A weak location was received, not quite clear from the previous waypoint... (%f more then max %f)",
                proposedLocation.getAccuracy(), this.mPreviousLocation.distanceTo(proposedLocation)));
        proposedLocation = addBadLocation(proposedLocation);
    }

    // Speed checks, check if the proposed location could be reached from the previous one in sane speed
    // Common to jump on network logging and sometimes jumps on Samsung Galaxy S type of devices
    if (this.mSpeedSanityCheck && proposedLocation != null && this.mPreviousLocation != null) {
        // To avoid near instant teleportation on network location or glitches cause continent hopping
        float meters = proposedLocation.distanceTo(this.mPreviousLocation);
        long seconds = (proposedLocation.getTime() - this.mPreviousLocation.getTime()) / 1000L;
        float speed = meters / seconds;
        if (speed > MAX_REASONABLE_SPEED) {
            Log.w(TAG,
                    "A strange location was received, a really high speed of " + speed + " m/s, prob wrong...");
            proposedLocation = addBadLocation(proposedLocation);
            // Might be a messed up Samsung Galaxy S GPS, reset the logging
            if (speed > 2 * MAX_REASONABLE_SPEED
                    && this.mPrecision != TrackingServiceConstants.LOGGING_GLOBAL) {
                Log.w(TAG, "A strange location was received on GPS, reset the GPS listeners");
                stopListening();
                // mLocationManager.removeGpsStatusListener(mStatusListener);
                this.mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                // sendRequestStatusUpdateMessage();
                // sendRequestLocationUpdatesMessage();
            }
        }
    }

    // Remove speed if not sane
    if (this.mSpeedSanityCheck && proposedLocation != null
            && proposedLocation.getSpeed() > MAX_REASONABLE_SPEED) {
        Log.w(TAG, "A strange speed, a really high speed, prob wrong...");
        proposedLocation.removeSpeed();
    }

    // Remove altitude if not sane
    if (this.mSpeedSanityCheck && proposedLocation != null && proposedLocation.hasAltitude()) {
        if (!addSaneAltitude(proposedLocation.getAltitude())) {
            Log.w(TAG, "A strange altitude, a really big difference, prob wrong...");
            proposedLocation.removeAltitude();
        }
    }
    // Older bad locations will not be needed
    if (proposedLocation != null) {
        this.mWeakLocations.clear();
    }
    return proposedLocation;
}

From source file:com.landenlabs.all_devtool.GpsFragment.java

private void showGPS(Location location) {
    if (location == null)
        return;// ww w. j  a  v a 2  s  . c  o m

    String provider = location.getProvider();
    LocInfo locInfo = m_mapLocProviders.get(provider);
    if (locInfo == null) {
        locInfo = new LocInfo();
        m_mapLocProviders.put(provider, locInfo);
    }

    locInfo.m_prevLocation = locInfo.m_currLocation;
    locInfo.m_currLocation = location;

    if (null != location) {
        addLocToDetailRow(locInfo);

        String msg = String.format("%8.5f,%9.5f %5.0fm %s", location.getLatitude(), location.getLongitude(),
                location.getAccuracy(), location.getProvider());
        GpsItem gpsItem = m_lastUpdates.get(provider);
        if (gpsItem != null) {
            gpsItem.set(location.getTime(), msg);
            listChanged();
        } else
            Ui.ShowMessage(this.getActivity(), "null text for " + provider); // DEBUG

    } else {
        m_gpsTv.setText("No location");
    }
}

From source file:com.uproot.trackme.LocationActivity.java

/**
 * Determines whether one Location reading is better than the current Location
 * fix. Code taken from http://developer.android.com/guide/topics/location
 * /obtaining-user-location.html/*  www . jav a 2 s.c o m*/
 * 
 * @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 The better Location object based on recency and accuracy.
 */
protected Location getBetterLocation(Location newLocation, Location currentBestLocation) {
    if (currentBestLocation == null) {
        // A new location is always better than no location
        return newLocation;
    }

    // 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 newLocation;
        // If the new location is more than two minutes older, it must be
        // worse
    } else if (isSignificantlyOlder) {
        return currentBestLocation;
    }

    // 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 newLocation;
    } else if (isNewer && !isLessAccurate) {
        return newLocation;
    } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
        return newLocation;
    }
    return currentBestLocation;
}