您可以尝试以下解决方法来解决“Android - FusedLocationClient,requestLocationUpdates()不返回结果和可用性奇怪的行为”问题:
确保您的设备已经启用了位置服务。可以在设备的设置中检查并启用位置服务。
确保您的应用程序具有适当的运行时权限。您可以使用以下代码请求运行时位置权限:
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
// 请求位置权限
private void requestLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// 如果权限尚未授予,则请求权限
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
} else {
// 权限已经授予,可以执行相应的操作
startLocationUpdates();
}
}
// 处理权限请求结果
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 权限已经授予,可以执行相应的操作
startLocationUpdates();
} else {
// 权限被拒绝,无法执行相应的操作
Toast.makeText(this, "Location permission denied", Toast.LENGTH_SHORT).show();
}
}
}
// 开始位置更新
private void startLocationUpdates() {
// 创建FusedLocationProviderClient对象
FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
// 设置位置请求参数
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(10000); // 10秒更新一次位置
locationRequest.setFastestInterval(5000); // 最快5秒更新一次位置
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); // 使用高精度模式
// 请求位置更新
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
请确保在调用startLocationUpdates()
之前已经获得了适当的位置权限。
private LocationCallback locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
// 处理位置更新
for (Location location : locationResult.getLocations()) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
// 处理位置数据
}
}
};
确保在处理位置更新时正确处理位置数据。
通过以上解决方法,您应该能够解决“Android - FusedLocationClient,requestLocationUpdates()不返回结果和可用性奇怪的行为”问题。