【发布时间】:2017-01-18 11:47:54
【问题描述】:
我正在尝试使用 GoogleApiClient 获取用户的位置,如果在活动开始时启用 GPS,它可以正常工作,但是,如果它未启用并且我要求用户启用 GPS,我不能似乎得到了位置。我正在尝试使用 LocationListener,我已经尝试过本地和 GooglePlayServices 侦听器。这是我的代码:
检查是否在 onCreate 中启用了 GPS:
//Ask the user to enable GPS if it is not.
mLocationRequestBalancedPowerAccuracy = new LocationRequest()
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
.setInterval(3600000)
.setFastestInterval(300000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequestBalancedPowerAccuracy);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(@NonNull LocationSettingsResult result) {
final Status status = result.getStatus();
//final LocationSettingsStates states = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(
MainActivity.this,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
Log.d("Location error", e.toString());
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
});
如果结果是 RESOLUTION REQUIRED,我运行 onResult 方法,如果用户接受启用 GPS,我将开始监听位置:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
switch (requestCode) {
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
// All required changes were successfully made
// User accepted to use GPS, start searching for location
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequestBalancedPowerAccuracy, this);
Log.d("locationmanager", "location result ok");
break;
case Activity.RESULT_CANCELED:
// The user was asked to change settings, but chose not to
this.finishAffinity();
break;
default:
break;
}
break;
}
}
一行 Log.d("locationmanager", "location result ok");已执行,但上面的行似乎没有执行。
最后是我的听众:
@Override
public void onLocationChanged(Location location) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.d("changed location", String.valueOf(location.getLatitude()) + " " + String.valueOf(location.getLongitude()));
}
【问题讨论】:
-
在 onConnected() 函数中发出位置请求。
-
我已经这样做了,但是如果启动时该位置不可用,则 onConnected 中的位置将为空。