Johan
Johan

Reputation: 35223

adding event listeners in onCreate

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!

Upvotes: 1

Views: 1873

Answers (2)

Simon Dorociak
Simon Dorociak

Reputation: 33515

Your approach is almost correct but step by step, there is no "good" reason to implement LocationListener in separated class but you should implement your LocationListener out of onCreate() method and

requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

is generally called rather in onResume() method and removeUpdates() in onDestroy() method.

I recommend to you check for example WeatherPlus application by CommonsWare and i think all will be clearer.

Upvotes: 1

Frank Sposaro
Frank Sposaro

Reputation: 8531

It really depends on what you want your application todo. So first I agree that is looks messy in the onCreate(). Let's say you write a little init() method and call that from your onCreate(), nothing has really changed yet. The only thing you have to pay attention to the Activity LifeCycle. If your registering to receive location updates than your Activity may get updates when your don't have screen focus. Another option is to move the register to onResume(), however you will need an unregister in onPause(). This will only get updates if your app is currently on the screen.

Upvotes: 1

Related Questions