How long ago was the last known location recorded?

android, geolocation, google-maps, gps, java

Solution

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

The pre 17 is not very accurate, but should be sufficient to test if a location is very old.

This, I should think, would be OK:

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.

Problem

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); ```

Original source