2

I have recently stared to get issues as my FusedLocationProviderClient doesn't call the onLocationResult() method of LocationCallback when the device location is already enabled but has no problems to do so when I ask user to enable the location himself first (disabled at first). Below I am posting my code (I do not show how I obtain location permission beforehand) called from onCreate():

public void onReady() {

    LocationRequest locReq = LocationRequest.create();

    LocationSettingsRequest request = new LocationSettingsRequest.Builder()
            .addLocationRequest(locReq)
            .build();
    LocationServices.getSettingsClient(this)
            .checkLocationSettings(request)
            .addOnCompleteListener(this::handleSettingsResponse);
}

private void handleSettingsResponse(Task<LocationSettingsResponse> task) {
        try {
            LocationSettingsResponse response = task.getResult(ApiException.class);
            if (response != null) {
                LocationSettingsStates states = response.getLocationSettingsStates();
                if (states.isLocationPresent() && states.isLocationUsable()) {
                    findLocation();
                } else {
                    failure()
                }
            }
        } catch (ApiException e) {
            copeWithFailure(e);
        }
    }

 private void copeWithFailure(Exception e) {
        if (e instanceof ResolvableApiException) {
            try {
                ((ResolvableApiException) e).startResolutionForResult(this, REQUEST_RESOLUTION);//I call findLocation() if successful
            } catch (IntentSender.SendIntentException e1) {
                failure()
            }
        }
    }

private void findLocation() {
        FusedLocationProviderClient client =
                LocationServices.getFusedLocationProviderClient(this);

        mLocationCallback = new LocationCallback() {

            @Override
            public void onLocationResult(LocationResult locationResult) {
                for (Location location : locationResult.getLocations()) {
                    startingLatitude = location.getLatitude();
                    startingLongitude = location.getLongitude();
                }}

        LocationRequest locaReq = LocationRequest()
            .setNumUpdates(1)
            .setExpirationDuration(5500)
            .setInterval(5000)
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        client.requestLocationUpdates(locaReq,
                mLocationCallback, Looper.getMainLooper())
                .addOnFailureListener(this, e -> {
                });
 }

This worked without problems before with pre-enabled location.

Androidz
  • 261
  • 2
  • 11

0 Answers0