Sunday 31 March 2013

Location


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.

Permission:
1. ACCESS_COARSE_LOCATION:
Required for NETWORK_PROVIDER.
2. ACCESS_FINE_LOCATION:
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.
      makeUseOfNewLocation(location);
    }
    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);

Note:
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);

Note:
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();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
/**
*  Get the critria list here(http://developer.android.com/reference/android/location/Criteria.html).
*/
String provider = locationManager.getBestProvider(criteria, true);

Note:
For detailed analysis, follow the doc.



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