我想实现一个LocationListener。检查了一些教程,发现了这一点:

/** 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);


}


但是在onCreate方法中是否真的添加了事件监听器?对我来说看起来很乱。将它们添加到单独的类并在onCreate中创建该类的实例是否更常见?我想了解这里的最佳做法。

谢谢!

最佳答案

您的方法几乎是正确的,但要一步一步来,没有“好的”理由在单独的类中实现LocationListener,但是您应该从LocationListener方法中实现onCreate()

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


通常在onResume()方法中称为,而在removeUpdates()方法中称为onDestroy()
我建议您检查一下CommonsWare的WeatherPlus应用程序,我认为一切都会更加清楚。

关于java - 在onCreate中添加事件监听器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11107490/

10-11 14:11