How long ago was the last known location recorded?(最后一个已知位置是多久前记录的?)
问题描述
我正在获取我最后一次知道的位置,但我不知道距离上次更新我的位置已有多长时间.我如何才能知道距离上次更新位置已有多长时间?
I am getting my last known location but not how long it has been since my location was last updated. How can I find out how long it has been since the location was last updated?
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);
推荐答案
API 17 前后的最佳选择:
Best option for both pre and post 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();
}
pre 17 不是很准确,但应该足以测试一个位置是否很旧.
The pre 17 is not very accurate, but should be sufficient to test if a location is very old.
我认为这样就可以了:
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
}
此逻辑的通常用例是应用刚刚启动时,我们需要知道我们是必须等待新位置还是在等待新位置时可以暂时使用最新位置位置.
The usual use case for this logic is when the app has just started and we need to know whether we must wait for a new location or can use the latest for now while we wait for a new location.
这篇关于最后一个已知位置是多久前记录的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:最后一个已知位置是多久前记录的?
基础教程推荐
- 从 python 访问 JVM 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
