1

我正在尝试使用FusedLocationProviderClient如下方式获取用户位置:

fusedLocationProviderClient.requestLocationUpdates(mLocationRequest, locationCallback, null);

我在此位置呼叫中获得位置更新

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

我读到locationResult.getLocations()检索从最旧到最新排序的位置对象列表,我不明白我现在想要的只是获取用户位置。

对此有任何帮助吗?

4

2 回答 2

1

您可以使用它locationResult.getLastLocation()来获取可用的最新位置。

来自文档:LocationResult.getLastLocation()

public Location getLastLocation ()
    Returns the most recent location 
    available in this result, or null if no 
    locations are available.
于 2018-04-07T12:07:30.767 回答
0

您可以使用LocationManager而不是FusedLocationProviderClient. 这可能会更容易。

    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);

这将在用户移动时为您提供位置。

于 2018-04-07T12:13:19.487 回答