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:
getLastLocation
and getLastKnownLocation
correct? Thanks
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With