2012-01-31 20 views
2

我每次加速度计值发生变化时都会从onSensorChanged()函数更新加速度计读数。然后创建一个文件,在这里我可以在每行上写入加速度计读数(X,Y,Z)轴,但也希望在每次读取之间添加时间间隔。我正在读的地方使用System.currentTimeMillis()是不是要走的路。尽可能准确地做到这一点的最好方法是什么?最可靠的计算时差的方法

回答

3

我建议使用SensorEvent的timestamp领域:

public long timestamp 

Since: API Level 3 
The time in nanosecond at which the event happened 

只要记住最后的值,并计算差值这样

+0

非常感谢你:) – unleashed 2012-01-31 19:59:14

+0

计算以前和当前时间戳是给我这样的值200012204.最后5个时间戳读数'28194580521720 28194780961176 28194980668203 28195180649892 28195380662101'正如你所看到的第6位总是变为1,3,5,7和9.我认为每个时间戳之间有20毫秒的差异? – unleashed 2012-01-31 20:53:05

+1

它广泛地取决于您正在运行的确切架构......这可能与手机有关,适用于Android。 – 2012-01-31 22:32:29

1

使用标准Java API调用:

System.nanoTime 

后来干脆时间之间的差异。

1

Guava'sStopwatch设计正是这种使用情况。

Stopwatch stopwatch = new Stopwatch().start(); 
doSomething(); 
stopwatch.stop(); // optional 

long millis = stopwatch.elapsedMillis(); 

log.info("that took: " + stopwatch); // formatted string like "12.3 ms"