首页 > 解决方案 > 请求位置更新从未调用 onLocationResult

问题描述

我正在使用 FusedLocationProvider 来获取手机的最后位置。不幸的是,返回的位置远非准确,并且没有更新!

即使当我调用 requestlocationupdates 时,OnlocationResult 也不会被 PRIORITY_HIGH_ACCURACY 调用。但它只用 PRIORITY_BALANCED_POWER_ACCURACY 调用一次。

protected void startLocationUpdates() {

    // Create the location request to start receiving updates
    locationRequest = new LocationRequest();
    locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    locationRequest.setInterval(5000);
    locationRequest.setFastestInterval(1000);
    // Create LocationSettingsRequest object using location request
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
    builder.addLocationRequest(locationRequest);
    LocationSettingsRequest locationSettingsRequest = builder.build();

    // Check whether location settings are satisfied
    // https://developers.google.com/android/reference/com/google/android/gms/location/SettingsClient
    SettingsClient settingsClient = LocationServices.getSettingsClient(this);
    Task<LocationSettingsResponse> task =settingsClient.checkLocationSettings(locationSettingsRequest);

    task.addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
        @Override
        public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
            // All location settings are satisfied. The client can initialize
            // location requests here.
            // ...
            Log.i("SRV", "onSuccess: Location settings are satisfied");
        }
    });

    task.addOnFailureListener( new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            if (e instanceof ResolvableApiException) {
                // Location settings are not satisfied, but this can be fixed
                // by showing the user a dialog.
                Log.i("SRV", "onFailure: ");
            }
        }
    });

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    Activity#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for Activity#requestPermissions for more details.
            initialized = false;
            //return;
        }
    }

    // new Google API SDK v11 uses getFusedLocationProviderClient(this)
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

    mFusedLocationClient.requestLocationUpdates(locationRequest, new LocationCallback() {
                @Override
                public void onLocationResult(LocationResult locationResult) {
                    super.onLocationResult(locationResult);
                    Log.i("SRV", "onLocationResult is called ");
                    if (locationResult == null) {
                        return;
                    }
                    for (Location location : locationResult.getLocations()) {
                        if (location != null) {
                            Log.i("SRV", "My new location is " + location.getLatitude() + " " + location.getLongitude());
                            onLocationChanged(location);
                        }
                    }
                }

                @Override
                public void onLocationAvailability(LocationAvailability locationAvailability) {
                    Log.i("SRV", "onLocationAvailability is called ");
                }

            },
            Looper.myLooper());

    //get last location
    mFusedLocationClient.getLastLocation().addOnSuccessListener(location -> {
        if (location != null) {
            _phoneLocation = location;
            Log.i("SRV", "getLastLocation is called :  My position " + location.getLatitude() + " " + location.getLongitude());
        }
    });
    Log.i("SRV", "Startlocation updated was completed succesfully");
}

我希望 OnlocationResult 会在 5 秒内被调用和更新。

标签: androidfusedlocationproviderapi

解决方案


事实证明,这是一件愚蠢的事情。我们在这方面花了太多时间。我在检查权限并允许它时遇到了一些问题。
在这里,我发布了完美运行的最终代码。确保在提示时允许位置权限。如果您要多次调试,建议先卸载应用程序重新允许权限。

public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION},
                1);
    } else if (mMap != null) {
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
    }

推荐阅读