这是我用于 locationlistener 的内容,使用与您相同的权限。
private void startLocationListener() {
userPosition.setPosition(myPosition);
// Get the location manager
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
if(currLocation != null)
{
boolean better = isBetterLocation(location, currLocation);
if(better)
{
currLocation.set(location);
myPosition = new LatLng(currLocation.getLatitude(), currLocation.getLongitude());
userPosition.setPosition(myPosition);
}
}
else
{
currLocation = location;
myPosition = new LatLng(currLocation.getLatitude(), currLocation.getLongitude());
userPosition.setPosition(myPosition);
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(GPSPROVIDER, 5000, 0, locationListener);
locationManager.requestLocationUpdates(NETPROVIDER, 30000, 0, locationListener);
}
protected boolean isBetterLocation(Location location, Location currentBestLocation) {
if (currentBestLocation == null) {
// A new location is always better than no location
return true;
}
// Check whether the new location fix is newer or older
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > TIME;
boolean isSignificantlyOlder = timeDelta < -TIME;
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location, use the new location
// because the user has likely moved
if (isSignificantlyNewer) {
return true;
// If the new location is more than two minutes older, it must be worse
} else if (isSignificantlyOlder) {
return false;
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(location.getProvider(),
currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and accuracy
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
return true;
}
return false;
}