要解决 Android FusedLocationProviderClient 不工作的问题,可以尝试以下解决方法:
private FusedLocationProviderClient fusedLocationClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
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);
}
}
@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) {
// 权限已授予,执行获取位置的逻辑
} else {
// 用户拒绝了权限请求,处理相应的逻辑
}
}
}
private void getLocation() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener() {
@Override
public void onSuccess(Location location) {
if (location != null) {
// 成功获取到位置信息,处理相应的逻辑
} else {
// 无法获取到位置信息,处理相应的逻辑
}
}
}).addOnFailureListener(this, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// 获取位置失败,处理相应的逻辑
}
});
} else {
// 没有位置权限,处理相应的逻辑
}
}
以上是一些可能解决 Android FusedLocationProviderClient 不工作问题的常见解决方法。请根据具体情况逐一尝试这些解决方法,并根据错误日志和调试信息进行进一步的调查和排查。