Age of location returned from LocationServices Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Age of location returned from LocationServices without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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?

Answer

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()

We are here to answer your question about Age of location returned from LocationServices - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji