Saturday 23 August 2014

Android: Location Listener app

In this demo we are going to fetch device current location using:

  • LocationListener
  • NETWORK_PROVIDER or GPS_PROVIDER 

First of all we have to set "uses-permission" in manifest:


As we are using both (NETWORK_PROVIDER  and GPS_PROVIDER ) we have to set ACCESS_FINE_LOCATION permission in manifest.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

First of all we will take user's input to update location , Here user can set how frequently user want to update its location.

According to Android documentation:
The minimum time interval for notifications, This field is only used as a hint to conserve power, and actual time between location updates may be greater or lesser than this value.

Now when user tries to get its current location, we have to check if location provider is enable or not.
If location provider is disable we can give user option to enable "Access to my location" from settings.


When user will enable "Access to my location" setting user will get back to our activity and user will see its current location, we are also changing background color of screen when "onLocationChanged" called.


About Code::::::::::::::

We have GpsLocator class which implements LocationListener.

LocationListener has following callback methods...

/* This method will be called when device location is changed.
Or according to MIN_TIME_BW_LOCATION_UPDATES parameter value.
Which we have set when application launch.
*/
       @Override
public void onLocationChanged(Location location) {

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

/*Called when gps enable
*/
@Override
public void onProviderEnabled(String provider) {
}

/*Called when gps disable
*/
@Override
public void onProviderDisabled(String provider) {
}


We have to register above LocationListner interace with LocationManager class.

locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, // Type of location provider it can be GPS_PROVIDER
MIN_TIME_BW_LOCATION_UPDATES, // Minimum time interval to update location
MIN_DISTANCE_CHANGE_FOR_LOCATION_UPDATES, // Minimum Distance to update location
this // Instance of LocationListner interface which we have implemented in this class
);

Andoid has provided demo code to check that currently fetched location is better than previous one or not.(Reference: http://developer.android.com/guide/topics/location/strategies.html). Which can be very helpful when we want to do some heavy operation on location changed or when our app functionality is depend on correct location.

You can download demo code from below URL:
https://drive.google.com/file/d/0B0mH97AUwQqheGJmbGN3UnF0Wlk/edit?usp=sharing



No comments:

Post a Comment