我是否需要使用FusedLocationProviderClient进行监听和回调?

问题描述 投票:0回答:2

我开始使用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...
}
android google-play-services android-location fusedlocationproviderclient
2个回答
0
投票

根据documentation获得lastKnownLocation()OnSuccessListener应该足够在极少数情况下位置可能为空。

个性我也在使用OnSuccessListener()


0
投票

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

但是,如果您想要精确定位并希望在用户移动时进行定期更新,那么您需要实现LocationCallback以继续获取位置更新。在这种情况下,您通常希望最后一个已知位置获取位置更新可能需要一些时间。

© www.soinside.com 2019 - 2024. All rights reserved.