我的应用程序在打开位置和设置优先级为HIGH时,当位置设置为关闭时,它可以正常工作,但当位置设置为GPS时,它崩溃了。LocationRequest.PRIORITY_LOW_POWER
而不是显示对话框来改变为 LocationRequest.PRIORITY_HIGH_ACCURACY
下面是访问SettingClient的方法
public void locationSettingRequest() {
LocationRequest mLocationRequestHighAccuracy = new LocationRequest().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationRequest mLocationRequestBalancedPowerAccuracy = new LocationRequest().setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequestHighAccuracy)
.addLocationRequest(mLocationRequestBalancedPowerAccuracy);
Task<LocationSettingsResponse> result =
LocationServices.getSettingsClient(this).checkLocationSettings(builder.build());
result.addOnCompleteListener(task -> {
try {
LocationSettingsResponse response = task.getResult(ApiException.class);
// All location settings are satisfied. The client can initialize location
// requests here.
getLoc();
} catch (ApiException exception) {
switch (exception.getStatusCode()) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the
// user a dialog.
try {
// Cast to a resolvable exception.
ResolvableApiException resolvable = (ResolvableApiException) exception;
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
resolvable.startResolutionForResult(
SignUpActivity.this,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
} catch (ClassCastException e) {
// Ignore, should be an impossible error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
break;
}
}
});
}
而我在OnActivityResult中收到了响应。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
if (requestCode == REQUEST_CHECK_SETTINGS) {
switch (resultCode) {
case Activity.RESULT_OK:
// All required changes were successfully made
getLoc();
break;
case Activity.RESULT_CANCELED:
finish();
break;
default:
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
我如何让位置从 LocationRequest.PRIORITY_LOW_POWER
到 HIGH_ACCURACY
?
我是这样解决的,我检查了一下是否有 LocationManager.NETWORK_PROVIDER
是启用的。如果没有,我就会显示一条信息,提示用户将位置模式改为 HIGH_ACCURACY
. 然后我打电话 settingRequest
如果 NETWORK_PROVIDER
是启用.不知道是否是正确的方法,但它的工作。
public void checkLocationMode() {
LocationManager loc = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (!loc.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Toast.makeText(this, "Turn location mode to High Accuracy.", Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
} else {
settingRequest();
}
}