Bugfix: use monotonic clock.

Fixes #800.
This commit is contained in:
Dennis Guse
2022-01-06 21:40:29 +01:00
parent 43e1c99642
commit 522d8b41d8
3 changed files with 42 additions and 4 deletions
@@ -0,0 +1,40 @@
package de.dennisguse.opentracks.services.handlers;
import android.os.SystemClock;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
/**
* A monotonic clock relative to the device's clock at time of the instantiation.
* Uses device time since startup.
* Replacement for java.time.Clock as it may not be monotonic (i.e., can jump back and forwards).
*/
public class MonotonicClock extends Clock {
private final long epochAtCreation;
private final long elapsedRealtimeAtCreation;
public MonotonicClock() {
epochAtCreation = Instant.now().toEpochMilli();
elapsedRealtimeAtCreation = SystemClock.elapsedRealtime();
}
@Override
public Instant instant() {
long current = (SystemClock.elapsedRealtime() - elapsedRealtimeAtCreation);
return Instant.ofEpochMilli(epochAtCreation + current);
}
@Override
public ZoneId getZone() {
throw new RuntimeException("Not implemented");
}
@Override
public Clock withZone(ZoneId zone) {
throw new RuntimeException("Not implemented");
}
}
@@ -30,7 +30,7 @@ public class TrackPointCreator implements BluetoothRemoteSensorManager.SensorDat
private final Callback service;
@NonNull
private Clock clock = Clock.systemUTC();
private Clock clock = new MonotonicClock();
private final GPSHandler gpsHandler;
private BluetoothRemoteSensorManager remoteSensorManager;
@@ -220,9 +220,7 @@ public class TrackStatistics {
@VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE)
public void addMovingTime(Duration time) {
if (time.isNegative()) {
// Needs implementation of a monotonic Clock #800
// throw new RuntimeException("Moving time cannot be negative");
return;
throw new RuntimeException("Moving time cannot be negative");
}
movingTime = movingTime.plus(time);
}