Determines the best Location . - Android Map

Android examples for Map:Location

Description

Determines the best Location .

Demo Code


//package com.java2s;

import android.location.Location;

public class Main {
    private static final int THRESHOLD_ACCURACY = 200;
    private static final int TWO_MINUTES = 1000 * 60 * 2;

    /**//from  w  w  w . j  a v a 2 s  .  c o m
     * Determines the best {@link Location}.
     * 
     * @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
     * @return <code>true</code> if <code>location</code> is a better location,
     *         <code>false</code> otherwise.
     */
    public static boolean isBetterLocation(final Location location,
            final Location currentBestLocation) {

        if (currentBestLocation == null)
            return true;

        final boolean isFromSameProvider = isSameProvider(
                location.getProvider(), currentBestLocation.getProvider());
        final float accuracyDelta = (location.getAccuracy() - currentBestLocation
                .getAccuracy());
        final boolean isLessAccurate = accuracyDelta > 0;
        final boolean isMoreAccurate = accuracyDelta < 0;
        final boolean isSignificantlyLessAccurate = accuracyDelta > THRESHOLD_ACCURACY;

        final long timeDelta = location.getTime()
                - currentBestLocation.getTime();
        final boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
        final boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
        final boolean isNewer = timeDelta > 0;

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

        if (isMoreAccurate)
            return true;
        else if (isNewer && !isLessAccurate)
            return true;
        else if (isNewer && !isSignificantlyLessAccurate
                && isFromSameProvider)
            return true;

        return false;
    }

    private static boolean isSameProvider(final String provider1,
            final String provider2) {
        if (provider1 == null)
            return provider2 == null;

        return provider1.equals(provider2);
    }
}

Related Tutorials