最后一个已知位置是多久前记录的? [英] How long ago was the last known location recorded?

查看:21
本文介绍了最后一个已知位置是多久前记录的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在获取我最后一次知道的位置,但我不知道距离上次更新我的位置已有多长时间.我如何才能知道距离上次更新位置已有多长时间?

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.

这篇关于最后一个已知位置是多久前记录的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆