您可能应该使用该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();
}
}
祝你好运!