I want to implement a LocationListener. Checked some tutorials and found this:
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.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.NETWORK_PROVIDER, 0, 0, locationListener);
}
But are event listeners really added in the onCreate method? Looks pretty messy to me. Is it more common to add them to a separate class and create an instance of the class in onCreate? I would like to know the best practices here.
Thanks!
Your approach is almost correct but step by step, there is no “good” reason to implement
LocationListenerin separated class but you should implement yourLocationListenerout ofonCreate()method andis generally called rather in
onResume()method andremoveUpdates()inonDestroy()method.I recommend to you check for example
WeatherPlusapplication by CommonsWare and i think all will be clearer.