我最近一直盯着问题,因为我FusedLocationProviderClient
没有调用设备位置已启用的onLocationResult()
方法,LocationCallback
但是当我要求用户先自己启用位置(起初禁用)时这样做没有问题。下面我发布了我的代码(我没有显示我如何事先获得位置许可)从以下位置调用onCreate()
:
public void onReady() {
LocationRequest locReq = LocationRequest.create();
LocationSettingsRequest request = new LocationSettingsRequest.Builder()
.addLocationRequest(locReq)
.build();
LocationServices.getSettingsClient(this)
.checkLocationSettings(request)
.addOnCompleteListener(this::handleSettingsResponse);
}
private void handleSettingsResponse(Task<LocationSettingsResponse> task) {
try {
LocationSettingsResponse response = task.getResult(ApiException.class);
if (response != null) {
LocationSettingsStates states = response.getLocationSettingsStates();
if (states.isLocationPresent() && states.isLocationUsable()) {
findLocation();
} else {
failure()
}
}
} catch (ApiException e) {
copeWithFailure(e);
}
}
private void copeWithFailure(Exception e) {
if (e instanceof ResolvableApiException) {
try {
((ResolvableApiException) e).startResolutionForResult(this, REQUEST_RESOLUTION);//I call findLocation() if successful
} catch (IntentSender.SendIntentException e1) {
failure()
}
}
}
private void findLocation() {
FusedLocationProviderClient client =
LocationServices.getFusedLocationProviderClient(this);
mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
startingLatitude = location.getLatitude();
startingLongitude = location.getLongitude();
}}
LocationRequest locaReq = LocationRequest()
.setNumUpdates(1)
.setExpirationDuration(5500)
.setInterval(5000)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
client.requestLocationUpdates(locaReq,
mLocationCallback, Looper.getMainLooper())
.addOnFailureListener(this, e -> {
});
}
这在使用预先启用的位置之前没有问题。