2011-10-07 44 views
5

我需要测量一段时间,可以持续几个小时。我假设正常的方式来做到这一点会是这样的:如何避免Android游戏中的时钟漏洞?

Date date = new Date(); 
...wait some time... 
(new Date()).getTime() - date.getTime()) 

,但可以更改用户的Android的时钟拨回一小时,骗取游戏,使时间跨度更短?从在线来源阅读时间是否是最佳解决方案?

回答

9

new Date()使用System.currentTimeMillis()这取决于操作系统时钟 - 并且可能随用户更改系统日期和时间而改变。

您应该使用System.nanoTime(),这具有以下特点:

/** 
* Returns the current value of the most precise available system 
* timer, in nanoseconds. 
* 
* <p>This method can only be used to measure elapsed time and is 
* not related to any other notion of system or wall-clock time. 
* The value returned represents nanoseconds since some fixed but 
* arbitrary time (perhaps in the future, so values may be 
* negative). This method provides nanosecond precision, but not 
* necessarily nanosecond accuracy. No guarantees are made about 
* how frequently values change. Differences in successive calls 
* that span greater than approximately 292 years (2<sup>63</sup> 
* nanoseconds) will not accurately compute elapsed time due to 
* numerical overflow. 
* 
* <p> For example, to measure how long some code takes to execute: 
* <pre> 
* long startTime = System.nanoTime(); 
* // ... the code being measured ... 
* long estimatedTime = System.nanoTime() - startTime; 
* </pre> 
* 
* @return The current value of the system timer, in nanoseconds. 
* @since 1.5 
*/ 
public static native long nanoTime(); 

这不能仅通过更改系统日期进行操作。

+0

完美,谢谢。 – FoppyOmega

+1

任何人都知道iOS SDK的等价物? – Tocco

+0

一个缺点是,当CPU被重置时nanoTime将被重置。这意味着您无法测量手​​机关机时的精确时间。 – sjkm