Android Basics : Learn how to track Location changes by adding a LocationListener

In order to use the Location Service you need to do the following:

  • Implement LocationListener
LocationListener locationListener = new LocationListener() {
    @Override
    public void onLocationChanged(Location location) {
        if (lastLocation == null) {
            lastLocation = location;
        }
        distanceInMetres += location.distanceTo(lastLocation);
    }

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

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
};
  • Create LocationManager using the Listener to start tracking user location changes
LocationManager locationManager = (LocationManager)
        getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this,
        Manifest.permission.ACCESS_FINE_LOCATION) != 
            PackageManager.PERMISSION_GRANTED
        && ActivityCompat.checkSelfPermission(this,
        Manifest.permission.ACCESS_COARSE_LOCATION) != 
            PackageManager.PERMISSION_GRANTED) {
    return;
}
locationManager.requestLocationUpdates(
        LocationManager.GPS_PROVIDER,
        1000,
        1,
        locationListener);
  • Add Permissions to the Manifest file.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

The Source Code for this implementation is available here

Author: androidsmartly

I am a Tech Enthusiast who likes to work on new Ideas. Sharing knowledge on Android, Marketing, Startups and More.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s