Skip to content

Commit 1fb807e

Browse files
committed
Android: calculate location age with elapsed real time if supported
1 parent 955dfa0 commit 1fb807e

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

android/src/main/java/com/agontuk/RNFusedLocation/FusedLocationProvider.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ public void getCurrentLocation(final LocationOptions locationOptions, final Loca
9090
@Override
9191
public void onSuccess(Location location) {
9292
if (location != null &&
93-
(System.currentTimeMillis() - location.getTime()) < locationOptions.getMaximumAge()
93+
LocationUtils.getLocationAge(location) < locationOptions.getMaximumAge()
9494
) {
9595
Log.i(RNFusedLocationModule.TAG, "returning cached location.");
9696
locationChangeListener.onLocationChange(location);

android/src/main/java/com/agontuk/RNFusedLocation/LocationManagerProvider.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ public void getCurrentLocation(LocationOptions locationOptions, LocationChangeLi
8181
Location location = locationManager.getLastKnownLocation(provider);
8282

8383
if (location != null &&
84-
(System.currentTimeMillis() - location.getTime()) < locationOptions.getMaximumAge()
84+
LocationUtils.getLocationAge(location) < locationOptions.getMaximumAge()
8585
) {
8686
Log.i(RNFusedLocationModule.TAG, "returning cached location.");
8787
locationChangeListener.onLocationChange(location);

android/src/main/java/com/agontuk/RNFusedLocation/LocationUtils.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import android.location.LocationManager;
77
import android.Manifest;
88
import android.os.Build;
9+
import android.os.SystemClock;
910
import android.text.TextUtils;
1011
import android.provider.Settings;
1112

@@ -19,6 +20,17 @@
1920
import com.google.android.gms.common.GoogleApiAvailability;
2021

2122
public class LocationUtils {
23+
/**
24+
* Calculates the age of a location fix in milliseconds
25+
*/
26+
public static long getLocationAge(Location location) {
27+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
28+
return (SystemClock.elapsedRealtimeNanos() - location.getElapsedRealtimeNanos()) / 1000000;
29+
}
30+
31+
return System.currentTimeMillis() - location.getTime();
32+
}
33+
2234
/**
2335
* Check if location permissions are granted.
2436
*/

0 commit comments

Comments
 (0)