Returns best location using LocationManager.getBestProvider() - Android Map

Android examples for Map:Location Provider

Description

Returns best location using LocationManager.getBestProvider()

Demo Code


//package com.java2s;

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

import android.location.Location;

import android.location.LocationManager;

public class Main {
    /**/*from  w ww . j  a va  2s. com*/
     * Returns best location using LocationManager.getBestProvider()
     * 
     * @param context
     * @return Location|null
     */
    public static Location getLocation(Context context) {
        System.out.println("getLocation()");

        // fetch last known location and update it
        try {
            LocationManager lm = (LocationManager) context
                    .getSystemService(Context.LOCATION_SERVICE);

            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
            criteria.setAltitudeRequired(false);
            criteria.setBearingRequired(false);
            criteria.setCostAllowed(true);
            String strLocationProvider = lm.getBestProvider(criteria, true);

            System.out
                    .println("strLocationProvider=" + strLocationProvider);
            Location location = lm
                    .getLastKnownLocation(strLocationProvider);
            if (location != null) {
                return location;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

Related Tutorials