2011-10-07 7 views
5

私は数時間続くことができる期間を測定する必要があります。Androidのゲームで時計の悪用を回避するにはどうすればよいですか?

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

しかし、ユーザーの変更Androidの時計背中時間ゲームをカンニングし、タイムスパンを短くすることができます:私はこれを行うには、通常の方法のようなものだろうと仮定していますか?オンラインソースからの読書時間は最善の解決策でしょうか?

答えて

9

new Date()は、OSクロックに依存する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

関連する問題