简体   繁体   English

使用位置回调获取位置更新

[英]Get location updates using location callbacks

I'm trying to get the user location using FusedLocationProviderClient as follows: 我正在尝试使用FusedLocationProviderClient获取用户位置,如下所示:

fusedLocationProviderClient.requestLocationUpdates(mLocationRequest, locationCallback, null);

I get location updates in this location calls 我在此位置通话中获得位置更新

 locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult); 
                for (Location location : locationResult.getLocations()) {
                    // list of locations
                }
            }
        };

I read that locationResult.getLocations() retrieves a list of location objects ordered from oldest to newest, I couldn't understand that all I want is to get the user location at the moment. 我读到了locationResult.getLocations()检索从旧到新排序的位置对象列表,我不明白我现在想要的只是获取用户位置。

Any help regarding this? 有什么帮助吗?

You can use locationResult.getLastLocation() to get the most up to date location available. 您可以使用locationResult.getLastLocation()获取最新的可用位置。

From the docs: LocationResult.getLastLocation() 从文档中: LocationResult.getLastLocation()

public Location getLastLocation ()
    Returns the most recent location 
    available in this result, or null if no 
    locations are available.

You could use LocationManager instead of FusedLocationProviderClient . 您可以使用LocationManager代替FusedLocationProviderClient It could be more easier. 可能会更容易。

    LocationManager manager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
    LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            Log.d("Current location", location.toString());
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }
    };
    //Checks permission
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

This will give you location when user moves. 当用户移动时,这将为您提供位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM