您應該使用LocationManager
對象來獲取和訪問位置更新。您可以查詢最近的已知位置以進行快速更新。
關鍵的是,我要求位置管理員開始傾聽,然後從那裏我可以隨時要求快速更新。我將更新的位置信息存儲在我的ApplicationContext
對象中(我在本地稱爲appModel
),該對象在對象的整個生命週期中都是持久的。
我使用LocationManager
這樣的:
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
startListening();
開始聽這個樣子的:
public void startListening() {
if (gpsLocationListener == null) {
// make new listeners
gpsLocationListener = new CustomLocationListener(LocationManager.GPS_PROVIDER);
// request very rapid updates initially. after first update, we'll put them back down to a much lower frequency
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 200, gpsLocationListener);
}
//get a quick update
Location networkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//this is the applicationContext object which persists for the life of the applcation
if (networkLocation != null) {
appModel.setLocation(networkLocation);
}
}
你位置監聽器看起來是這樣的:
private class CustomLocationListener implements LocationListener {
private String provider = "";
private boolean locationIsEnabled = true;
private boolean locationStatusKnown = true;
public CustomLocationListener(String provider) {
this.provider = provider;
}
@Override
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
handleLocationChanged(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
startListening();
}
public void onProviderDisabled(String provider) {
}
}
private void handleLocationChanged(Location location) {
if (location == null) {
return;
}
//get this algorithm from: http://developer.android.com/guide/topics/location/obtaining-user-location.html
if (isBetterLocation(location, appModel.getLocation())) {
appModel.setLocation(location);
stopListening();
}
}
祝你好運!