Android LocationServices.checkLocationSettings方法是用来检查设备是否启用了位置服务。然而,它有一些局限性,可能会导致返回假负结果(即设备实际上启用了位置服务,但该方法返回错误结果)。
以下是避免出现false negative结果的建议:
使用最新的Google Play服务库。
在调用LocationServices.checkLocationSettings方法之前,确保已经请求了相应的位置权限。
检查设备的位置设置并确保它们符合您的应用程序的要求。您可以使用LocationRequest对象来指定应用程序的位置精度要求和更新频率。
以下是使用LocationRequest对象的示例代码:
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(10000); // 10 seconds
locationRequest.setFastestInterval(5000); // 5 seconds
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true); // Show dialog if location services are not enabled
PendingResult result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient,
builder.build());
result.setResultCallback(new ResultCallback() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can initialize location
// requests here.
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(
MainActivity.this,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we