我是否需要使用FusedLocationProviderClient的侦听器和回调?

时间:2019-04-23 08:52:09

标签: android google-play-services android-location fusedlocationproviderclient

我开始使用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...
}

2 个答案:

答案 0 :(得分:0)

根据documentation,当获取lastKnownLocation()时,OnSuccessListener应该足够了,在极少数情况下Location可能为空。

个性我也在使用OnSuccessListener()

答案 1 :(得分:0)

如果您此时不对用户的确切位置感兴趣,那么lastKnownLocation()和OnSuccessListener就足够了,并且您不需要LocationCallback。

但是,如果您想要精确的位置并且需要定期更新以防用户在移动中,则您需要实现LocationCallback以保持位置更新。在这种情况下,您通常需要最后一个已知的位置,因为获取位置更新可能需要一些时间。