我正在Android OS上开发一款应用.我不知道如何检查是否启用了位置服务.
我需要一个方法,如果它们被启用则返回"true",否则返回"false"(所以在最后一种情况下我可以显示一个对话框来启用它们).
在获取当前位置流时,我正在使用SettingsClient根据当前LocationRequest来检查是否满足位置设置。目前,我的优先级设置为HIGH_ACCURACY,这需要不惜一切代价启用GPS。
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
settingsClient = LocationServices.getSettingsClient(this);
locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(500)
.setFastestInterval(500);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(locationRequest);
locationSettingsRequest = builder.build();
Run Code Online (Sandbox Code Playgroud)
现在,当我调用给它提供侦听器的SettingsClient.checkLocationSettings()时,
settingsClient.checkLocationSettings(locationSettingsRequest)
.addOnCompleteListener(this)
.addOnFailureListener(this);
Run Code Online (Sandbox Code Playgroud)
它属于onFailure(),在这种情况下,github上的google官方示例采用以下方法;
检查在onFailure()中接收到的异常的状态码(如果它是LocationSettingsStatusCodes.RESOLUTION_REQUIRED),然后调用startResolutionForResult(),它允许我们启用GPS,这将等待使用onActivityResult的结果。
@Override
public void onFailure(@NonNull Exception e) {
int statusCode = ((ApiException) e).getStatusCode();
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
// Show the dialog by calling startResolutionForResult(), and check the
// result in onActivityResult().
ResolvableApiException rae = (ResolvableApiException) e;
rae.startResolutionForResult(LocationActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException sie) {
showLocationError();
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: …
Run Code Online (Sandbox Code Playgroud)