Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LocationManager and LocationClient together to get user location

I simply need to get the user location. Preferably the exactly location, but if it's not possible, a rough location would be fine.

According to the docs:

LocationClient.getLastLocation()

Returns the best most recent location currently available.

and

LocationManager.getLastKnownLocation(String)

Returns a Location indicating the data from the last known location fix obtained from the given provider.

If my understanding is right, the former will give me a very good result (or null sometimes) while the latter will give me a result which would rarely be null.

This is my code (simplified)

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationClient = new LocationClient(this, this, this);

@Override
public void onConnected(Bundle dataBundle) {
    setUserLocation();
}

private void setUserLocation() {
    myLocation = locationClient.getLastLocation();

    if (myLocation == null) {
        myLocation = locationManager.getLastKnownLocation(locationManager.getBestProvider(new Criteria(), false));
        if (myLocation == null) {
            //I give up, just set the map somewhere and warn the user.
            myLocation = new Location("");
            myLocation.setLatitude(-22.624152);
            myLocation.setLongitude(-44.385624);
            Toast.makeText(this, R.string.location_not_found, Toast.LENGTH_LONG).show();
        }
    } else {
        isMyLocationOK = true;
    }
}

It seems to be working but my questions are:

  1. Is my understanding of getLastLocation and getLastKnownLocation correct?
  2. Is this a good approach?
  3. Can I get in trouble using both in the same activity?

Thanks

like image 730
Androiderson Avatar asked Jun 25 '13 17:06

Androiderson


1 Answers

LocationClient.getLastLocation() only returns null if a location fix is impossible to determine. getLastLocation() is no worse than getLastKnownLocation(), and is usually much better. I don't think it's worth "falling back" to getLastKnownLocation() as you do.

You can't get into trouble using both, but it's overkill.

Of course, you have to remember that LocationClient is part of Google Play Services, so it's only available on devices whose platform includes Google Play Store. Some devices may be using a non-standard version of Android, and you won't have access to LocationClient.

The documentation for Google Play Services discusses this in more detail.

like image 168
Joe Malin Avatar answered Oct 14 '22 12:10

Joe Malin