多久以前记录的最后一个位置?

mad*_*ddy 14 java gps android google-maps geolocation

我正在获取我最后一个已知位置,但不知道自我的位置上次更新以来已经有多长时间了.如何查看自上次更新位置以来已经过了多长时间?

LocationManager locationManager 
                        = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria c = new Criteria();
    c.setAccuracy(Criteria.ACCURACY_FINE);
    c.setAccuracy(Criteria.ACCURACY_COARSE);
    c.setAltitudeRequired(false);
    c.setBearingRequired(false);
    c.setCostAllowed(true);
    c.setPowerRequirement(Criteria.POWER_HIGH);
String provider = locationManager.getBestProvider(c, true);
Location location = locationManager.getLastKnownLocation(provider);
Run Code Online (Sandbox Code Playgroud)

wes*_*ton 24

API 17之前和之后的最佳选择:

public int age_minutes(Location last) {
    return age_ms(last) / (60*1000);
}

public long age_ms(Location last) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
        return age_ms_api_17(last);
    return age_ms_api_pre_17(last);
}

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private long age_ms_api_17(Location last) {
    return (SystemClock.elapsedRealtimeNanos() - last
            .getElapsedRealtimeNanos()) / 1000000;
}

private long age_ms_api_pre_17(Location last) {
    return System.currentTimeMillis() - last.getTime();
}
Run Code Online (Sandbox Code Playgroud)

前17不是很准确,但应足以测试位置是否很旧.

我认为,这可以:

if (age_minutes(lastLoc) < 5) {
   // fix is under 5 mins old, we'll use it

} else {
   // older than 5 mins, we'll ignore it and wait for new one

}
Run Code Online (Sandbox Code Playgroud)

这个逻辑的通常用例是当应用程序刚刚启动时,我们需要知道我们是否必须等待新位置,或者在我们等待新位置时可以使用最新版本.


Ger*_*esp 7

很抱歉重新打开这个,但我认为weston的答案是不正确的,Android文档至少是误导性的.

getTime()的时基是从GPS模块接收的NMEA语句确定的UTC,而不是 System.currentTimeMillis().GPS时间精确到纳秒(必须是因为电磁波在1ns内行进30cm).这里唯一的复杂因素是,由于GPS闰秒,它可能会偏离1秒(参见[1];这可能发生在每几年几分钟内,假设GPS足够智能以记住电源周期内的UTC偏移) )

另一方面,如果用户不正确地设置时间/日期,System.currentTimeMillis()可能因漂移而关闭几秒/分钟甚至更多.

因此,API 17之前唯一真正的解决方案是定期接收位置更新,并且每次都根据SystemClock.elapsedRealtime()记录您自己的时间戳.

我刚刚在三星S4上试过这个,如果其他手机给出不同的结果,请纠正我.不过我对此表示怀疑.

[1] http://en.wikipedia.org/wiki/Global_Positioning_System#Leap_seconds


sti*_*vlo 5

Location.getTime()实际上不是查找上一个已知位置的年龄的最佳方法.

来自JavaDoc:

返回此修复的UTC时间,以1970年1月1日以来的毫秒数为单位.

请注意,设备上的UTC时间不是单调的:它可以无法预测地向前或向后跳跃.所以在计算时间增量时总是使用getElapsedRealtimeNanos.

使用的两种方法是:

SystemClock.elapsedRealtimeNanos();
Location.getElapsedRealtimeNanos();
Run Code Online (Sandbox Code Playgroud)

另请注意,LocationManager.lastKnownLocation()可能返回null.