我有以下课程,我所有的活动都对其进行了扩展,我想在其中使用LocationServices保存最后的位置。
调试似乎已授予权限,然后输入onComplete方法,但task.getResult()始终为null。这怎么可能?
public class MyAppCompatActivity extends AppCompatActivity {
private static final int LOCATION_REQUEST_CODE = 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
LOCATION_REQUEST_CODE);
} else
setUserLocation();
}
@Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
switch (requestCode) {
case LOCATION_REQUEST_CODE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
setUserLocation();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request.
}
}
@SuppressLint("MissingPermission")
private void setUserLocation() {
LocationServices.getFusedLocationProviderClient(this).getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
ROUserInfo user = UserManager.getROUserInfo();
if(user==null || task.getResult()==null)
return;
user.User._Position._Latitude=task.getResult().getLatitude();
user.User._Position._Longitude=task.getResult().getLongitude();
UserManager.updateUserOnServer(user);
}
});
}
}