I need to ensure the location I use is fresh:
Is there a way of finding out how old the location result returned by LocationServices.FusedLocationApi.getLastLocation
is?
If not: if I register a location listener to the LocationServices.FusedLocationApi.requestLocationUpdates
(with setNumUpdates(1)
and setMaxWaitTime(0)
) then will it update if the location has not changed from the one returned by LocationServices.FusedLocationApi.getLastLocation
?
Yes, there is a very easy way. You can get the time of a Location fix by calling getTime()
like this:
Location currentLocation = LocationServices.FusedLocationApi.getLastLocation(apiClient);
long locationAge = System.currentTimeMillis() - currentLocation.getTime();
if (locationAge <= 60 * 1000) { // not older than 60 seconds
// do something with the location
}
The documentation recommends not to use System.currentTimeMillis() for time comparisons, but I never experienced any flaws with this method. However, you should consider reading the (short) documentation:
https://developer.android.com/reference/android/location/Location.html#getTime()