Search code examples
androidgeolocationposition

Fused Location Issue - Geo localization not work


I have to implement a function that return the current geo position of the user using one of the all the sensor available (e.g. wifi, gps, data ecc).

I looked for information about it and I found several solutions, the one that currently interests me is the use of the "fused location", but I did not find is a guide or a complete example of use.

This is the code that I currently use:

public class LocationService extends Service {

private FusedLocationProviderClient mFusedLocationClient;
private SettingsClient mSettingsClient;
private LocationRequest mLocationRequest;
private LocationSettingsRequest mLocationSettingsRequest;
private LocationCallback mLocationCallback;
private Location mCurrentLocation;
private Boolean mRequestingLocationUpdates;
private WriteInLogFile wil = new WriteInLogFile();

@Override
public void onCreate() {
    try {
        DbGest db = DbGest.getInstance(getApplicationContext());
        String deviceType = db.getSetting("deviceType");

        long updateInterval;
        if (deviceType.compareToIgnoreCase("smartphone") == 0) {
            updateInterval = Long.parseLong(db.getSetting("pollGPSPhone"));
        } else {
            updateInterval = Long.parseLong(db.getSetting("pollGPSTablet"));
        }

        long updateInMillisecond = updateInterval / 2;

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(updateInterval);
        mLocationRequest.setFastestInterval(updateInMillisecond);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);


        mRequestingLocationUpdates = false;
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        mSettingsClient = LocationServices.getSettingsClient(this);

        mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);
                mCurrentLocation = locationResult.getLastLocation();
                updateLocation();
            }
        };


        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
        builder.addLocationRequest(mLocationRequest);
        builder.setNeedBle(true);
        mLocationSettingsRequest = builder.build();
        startLocationUpdates();
    } catch (Exception e) {
        wil.WriteFile("1)LocationService - Exception: " + e.toString());
    }
}


public void startLocationUpdates() {
    if (!mRequestingLocationUpdates) {
        mRequestingLocationUpdates = true;
        mSettingsClient.checkLocationSettings(mLocationSettingsRequest).addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
            @Override
            public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                wil.WriteFile("2)LocationService - Exception: " + e.toString());
            }
        });
    }
}


private void stopLocationUpdates() {
    if (!mRequestingLocationUpdates) {
        return;
    }
    mFusedLocationClient.removeLocationUpdates(mLocationCallback).addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            mRequestingLocationUpdates = false;
        }
    });
}


private void updateLocation() {
    if (mCurrentLocation != null) {   
    DbGest.getInstance(getApplicationContext()).insertIntoLastPositionKnown(mCurrentLocation, getApplicationContext());
    }
}

@Override
public void onDestroy() {
    super.onDestroy();
    stopLocationUpdates();
}

@Override
public IBinder onBind(Intent intent) {
    return null;
} }

The code work if i'm connected via Wi-Fi to the network in this case all work perfectly, but when I switch in 3g an error occours:

com.google.android.gms.common.api.ResolvableApiException: 6: RESOLUTION_REQUIRED

In gradle:

compile 'com.google.android.gms:play-services-gcm:11.6.2'
compile 'com.google.android.gms:play-services-vision:11.6.2'
compile 'com.google.android.gms:play-services-location:11.6.2'
compile 'com.google.android.gms:play-services-maps:11.6.2'

I have no idea to solve this problem...


Solution

  • Getting location might get some time and I would suggest handling it in the background would make the experience smoother. Check whether you got the permission and the permission has been enabled in your app. Please post the Log if you need further assistance. I've tried this code and works fine!

        private void getUserLocation() {
        FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            mFusedLocationClient.getLastLocation()
                    .addOnSuccessListener(new OnSuccessListener<Location>() {
                        @Override
                        public void onSuccess(Location location) {
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    });
        }
    }