Extract the latest location information from the device's location store. - Android Map

Android examples for Map:Location

Description

Extract the latest location information from the device's location store.

Demo Code

/* **************************************************
Copyright (c) 2014, University of Birmingham
Karthikeya Udupa, kxu356@bham.ac.uk/*from  w w  w  . j  a  v  a 2  s.  com*/

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 ************************************************** */
//package com.java2s;

import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;

public class Main {
    /**
     * Extract the latest location information from the device's location store.
     * @param context
     * @return
     */
    public static Location getLatestLocation(Context context) {

        LocationManager manager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        String provider = manager.getBestProvider(criteria, true);
        Location bestLocation;
        if (provider != null)
            bestLocation = manager.getLastKnownLocation(provider);
        else
            bestLocation = null;
        Location latestLocation = getLatest(bestLocation,
                manager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
        latestLocation = getLatest(
                latestLocation,
                manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER));
        latestLocation = getLatest(
                latestLocation,
                manager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER));
        return latestLocation;
    }

    /**
     * Compares location for freshness.
     * @param location1
     * @param location2
     * @return
     */
    private static Location getLatest(final Location location1,
            final Location location2) {
        if (location1 == null)
            return location2;

        if (location2 == null)
            return location1;

        if (location2.getTime() > location1.getTime())
            return location2;
        else
            return location1;
    }
}

Related Tutorials