我想实现一个LocationListener
。经过一些教程,发现这个:在onCreate中添加事件侦听器
/** 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
中创建类的实例更常见吗?我想知道这里的最佳做法。
谢谢!
我猜的愚蠢问题,但如果我调用'onCreate'之外的'requestLocationUpdates',我将如何得到最后一个参数'locationListener'?在类中创建它作为一个私有变量,并在'onCreate'中初始化它? – Johan
这很简单,只需创建'LocationListener onLocationChange = new LocationListener(){};'通常在'onCreate()'之外,就像创建普通方法一样。然后只需调用'mgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t 10000,10000。0f,onLocationChange);' – Sajmon
感谢您的阐述! – Johan