0

我需要确保我使用的位置是新鲜的:

有没有办法找出返回的位置结果有多老LocationServices.FusedLocationApi.getLastLocation

LocationServices.FusedLocationApi.requestLocationUpdates如果不是:如果我向(with setNumUpdates(1)and )注册了一个位置侦听器,setMaxWaitTime(0)那么如果位置没有从返回的位置更改,它会更新LocationServices.FusedLocationApi.getLastLocation吗?

4

2 回答 2

4

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

于 2015-09-11T11:14:01.867 回答
2

为了扩展 Illiminat 的答案,从 API 17 开始,该getElapsedRealtimeNanos()方法已被添加。从方法的文档...

从系统启动后实时返回此修复的时间。

该值可以可靠地与 SystemClock.elapsedRealtimeNanos() 进行比较,以计算修复的年龄并比较位置修复。这是可靠的,因为每次系统启动都保证了经过的实时时间是单调的,并且即使系统处于深度睡眠状态也会继续增加(与 getTime() 不同)。

https://developer.android.com/reference/android/location/Location.html#getElapsedRealtimeNanos()

因此,以下现在应该是计算这个的最精确的方法

Location currentLocation = LocationServices.FusedLocationApi.getLastLocation(apiClient);
long locationAge = SystemClock.elapsedRealtimeNanos() - currentLocation.getElapsedRealtimeNanos();
long ageLimitNanoSec = 60_000_000_000; // 60 seconds in nano seconds
if (locationAge <= ageLimitNanoSec) { 
    // do something with the location
}
于 2020-01-13T15:38:42.707 回答