Alaa M.
Alaa M.

Reputation: 5273

Can't get location without wifi

Whatever I do, I just can't get current location without wifi enabled. This code works only when wifi is enabled:

if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
    provider = LocationManager.GPS_PROVIDER;
else if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
    provider = LocationManager.NETWORK_PROVIDER;
else if(locationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER))
    provider = LocationManager.PASSIVE_PROVIDER;

Location location = locationManager.getLastKnownLocation(provider);

When wifi is disabled, location is null.

And the following code never works (even if wifi is enabled):

protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

in onCreate():

buildGoogleApiClient();

in onStart():

mGoogleApiClient.connect();

And here's onConnected():

@Override
public void onConnected(Bundle connectionHint) {
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    if(mLastLocation == null)
    {
        disableButtons();
    }
    else
    {
        String userLocation = FindLocation.getLocatoinName(mLastLocation);
        userLocationDetails = new LocationStruct(mLastLocation.getLatitude(), mLastLocation.getLongitude(), userLocation);
    }
}

Inside onConnected(), mLastLocation is always null.

I tried on 2 phones: Lenovo A820 API 16 and Samsung Galaxy S4 API 19. Same result on both phones.

Upvotes: 0

Views: 524

Answers (1)

Sharp Edge
Sharp Edge

Reputation: 4192

You cannot rely on Last Known Location to always be available. In your onConnected() you're only checking for the last known location.

You have to create a LocationRequest in your onConnected()

mLocationRequest = LocationRequest.create()
            .setPriority(locationPriority) // LocationRequest.PRIORITY_HIGH_ACCURACY
            .setInterval(10 * 1000)        // 10 * 1000 10 seconds, in milliseconds
            .setFastestInterval(1 * 1000);

Then you have to request location updates:

LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

You'll then get Location in onLocationChanged(Location location)

Upvotes: 1

Related Questions