How to Add a LocationListener

LocationListener was added in API Level 1
Used for receiving notifications from the LocationManager when the location has changed. These methods are called if the LocationListener has been registered with the location manager service using the requestLocationUpdates(String, long, float, LocationListener) method.


1. In the MainActivity.java file, add the below to the import section.

import android.location.LocationListener;

2. Add the below code to the onCreate method. This will add a LocationListener named myLocationListener. Toasts were added for testing.

LocationListener myLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
//Update application based on new location
//Toast.makeText(getBaseContext(), "onLocationChanged", Toast.LENGTH_LONG).show();
}

public void onProviderDisabled(String provider) {
//update application if provider disabled
//Toast.makeText(getBaseContext(), "onProviderDisabled", Toast.LENGTH_LONG).show();
}

public void onProviderEnabled(String provider) {
//update application if provider enabled
//Toast.makeText(getBaseContext(), "onProviderEnabled", Toast.LENGTH_LONG).show();
}

public void onStatusChanged(String provider, int status, Bundle extras) {
// update application if provider hardware status changed
//Toast.makeText(getBaseContext(), "onStatusChanged", Toast.LENGTH_LONG).show(); switch (status) { case LocationProvider.AVAILABLE: Toast.makeText(getBaseContext(), "GPS available", Toast.LENGTH_LONG).show(); break; case LocationProvider.OUT_OF_SERVICE: Toast.makeText(getBaseContext(), "GPS out of service", Toast.LENGTH_LONG).show(); break; case LocationProvider.TEMPORARILY_UNAVAILABLE: Toast.makeText(getBaseContext(), "GPS temporarily unavailable", Toast.LENGTH_LONG).show(); break; }
}
};

3. Compile and run!

Resources:
Professional Android 4 Application Development by Reto Meier, pg 522
http://developer.android.com/reference/android/location/LocationListener.html
http://stackoverflow.com/questions/4772686/location-managers-requestlocationupdates-called-only-once