Are you trying to calculate the time duration between two events? better don't use `System.currentTimeMillis()`. use `SystemClock.elapsedRealtime()` instead.
System.currentTimeMillis()
will give you the standard "wall" clock (time and date) expressing milliseconds since the epoch. The wall clock can be set by the user or the phone network (see setCurrentTimeMillis(long)
), so the time may jump backwards or forwards unpredictably.SystemClock.elapsedRealtime()
return the time in milliseconds since the system was booted, and include deep sleep. This clock is guaranteed to be monotonic, and continues to tick even when the CPU is in power saving modes, so is the recommend basis for general purpose interval timing. Use elapsedRealtimeNanos()
to get this `realTime` in nanoseconds. For example, you want to calculate a method execution time System.currentTimeMillis()
read current time at starting of method execution and store in a variable
long startTime = System.currentTimeMillis();
|
>> But what will happen if we change the time which is running the system/device. We have a fair chance of changing the device time by the user of your application right?
|
read current time at ending of method execution and store in a variable
long endTime = System.currentTimeMillis();
calculate the difference between startTime and endTime to get the answer
long duration = endTime - startTime;
Use SystemClock.elapsedRealtime() instead of System.currentTimeMillis() to not get effected by time setting changes.
read current time at starting of method execution
long startTime = SystemClock.elapsedRealtime();
read current time at ending of method executio
long endTime = SystemClock.elapsedRealtime();
calculate the difference
long duration = endTime - startTime;