我一直在尝试使用 android 中的 FusedLocationProviderClient 获取当前位置数据。我总是在位置变量上得到空值,我该如何解决?
我试图按照 FusedLocationProviderClient 的 android 开发者网站的步骤进行操作,但没有帮助。
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context, "Location permission Required", Toast.LENGTH_SHORT).show();
} else {
mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
mLocation = location;
Log.d(TAG, "getLocation: "+mLocation.getLatitude()+","+mLocation.getLongitude());
}
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(20 * 1000);
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
if (locationResult == null) {
return;
} else {
for (Location location : locationResult.getLocations()) {
if (location != null) {
mLocation = location;
Log.d(TAG, "getLocation: "+mLocation.getLatitude()+","+mLocation.getLongitude());
}
}
}
}
};
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context, "No Location Permission", Toast.LENGTH_SHORT).show();
}
else {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
}}
});
我希望此代码返回当前位置数据。