问题描述: 在Android应用中使用FusedLocationProviderClient获取设备的位置信息时,有时候无法正常工作。
解决方法:
implementation 'com.google.android.gms:play-services-location:18.0.0'
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGpsEnabled && !isNetworkEnabled) {
// 提示用户打开位置设置
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// 请求位置权限
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE);
} else {
// 已有权限,执行获取位置信息的操作
startLocationUpdates();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 用户授予了权限,执行获取位置信息的操作
startLocationUpdates();
} else {
// 用户拒绝了权限请求,处理相应的逻辑
}
}
}
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
然后,在调用FusedLocationProviderClient的方法之前,使用以下代码检查并提示用户打开位置设置:
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
SettingsClient settingsClient = LocationServices.getSettingsClient(this);
Task task = settingsClient.checkLocationSettings(builder.build());
task.addOnSuccessListener(this, new OnSuccessListener() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
// 位置设置正常,执行获取位置信息的操作
startLocationUpdates();
}
});
task.addOnFailureListener(this, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
if (e instanceof ResolvableApiException) {
try {
// 提示用户打开位置设置
ResolvableApiException resolvable = (ResolvableApiException) e;
resolvable.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException sendEx) {
// 处理异常情况
}
}
}
});
以上是一些常见的解决方法,可以根据具体情况进行调整和组合使用。如果问题仍然存在,建议查看日志输出,以便更好地定位和解决问题。