Sunday, 31 March 2013


To find the location of user, comes with cost and cost includes battery, CPU etc.
Android provides two way to get the user location:

1. Network Provider:
a) It uses cell tower and wifi signals. 
b) It works indoor and outdoor both.
c) It consumes less battery and takes less time to give result.

2. GPS Provider:
a) It is more accurate than Network Provider.
b) It works only outdoor.
c) It consumes more battery and takes more time to give result.

Required for GPS_PROVIDER. It includes permission for NETWORK_PROVIDER too. Use this if you are using both provider.

To get the location, we need to register the listner(LocationListener) with LocationManager:

// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
      // Called when a new location is found by the network location provider.
    public void onStatusChanged(String provider, int status, Bundle extras) {}
    public void onProviderEnabled(String provider) {}
    public void onProviderDisabled(String provider) {}

// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER/LocationManager.NETWORK_PROVIDER, min_time_interval, min_distance_change, locationListener);

1) Setting min_time_interval and min_distance_change to 0 receives the updates as frequently as possible.
2) To get the location updates from both provider, you need to register twice one with GPS_PROVIDER and second with NETWORK_PROVIDER.

Getting Location while registering:
You will not get location as soon as you register, it takes time. So for first time
we can use the last cached location.

String locationProvider = LocationManager.NETWORK_PROVIDER;
// Or use LocationManager.GPS_PROVIDER
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);

It may happen that last received location is more accurate than the newest one.
How to Know which provider to use?
If you are not sure  know about the best provider for your requirments then you can use Criteria class:

Criteria criteria = new Criteria();
*  Get the critria list here(
String provider = locationManager.getBestProvider(criteria, true);

For detailed analysis, follow the doc.

profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers

No comments:

Post a Comment