我想實現一個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