LocationManager and LocationClient together to get user location

I just need to get the location of the user. An exact location is preferred, but if this is not possible, an approximate location will be good.

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 correct, the former will give me a very good result (or null sometimes), while the latter will give me a result that 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 like I'm working, but my questions are:

  • Is my understanding of getLastLocation and getLastKnownLocation ?
  • Is this a good approach?
  • Can I get into a problem using both in one activity?

thanks

+8
android location
source share
1 answer

LocationClient.getLastLocation() returns null only if the location cannot be determined. getLastLocation() no worse than getLastKnownLocation() , and usually much better. I don’t think it's worth “backing down” to getLastKnownLocation() , just like you.

You may not encounter difficulties using both options, but this is overkill.

Of course, you must remember that LocationClient is part of the Google Play Services, so it is only available on devices whose platform includes the Google Play Store. Some devices may use a non-standard version of Android, and you will not have access to LocationClient .

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

+7
source share

All Articles