我开始使用FusedLocationClient,我不知道为什么我需要OnSuccessListener和LocationCallback。不应该只是其中一个足够吗?
private void initLocationCallback(Context context) {
fusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
fusedLocationClient.getLastLocation()
.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
onLocationChanged(location);
}
});
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult != null) {
for (Location location : locationResult.getLocations()) {
if (location != null) {
onLocationChanged(location);
}
}
}
}
};
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(INTERVAL);
locationRequest.setFastestInterval(FASTEST_INTERVAL);
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, context.getMainLooper());
}
private void onLocationChanged(Location location) {
// use location...
}
根据documentation获得lastKnownLocation()
,OnSuccessListener
应该足够在极少数情况下位置可能为空。
个性我也在使用OnSuccessListener()
如果您在这个精确的时刻对用户的确切位置不感兴趣,那么lastKnownLocation()和OnSuccessListener就足够了,您不需要LocationCallback。
但是,如果您想要精确定位并希望在用户移动时进行定期更新,那么您需要实现LocationCallback以继续获取位置更新。在这种情况下,您通常希望最后一个已知位置获取位置更新可能需要一些时间。