在Andriod中关于计算时间的操作,SystemClock类。
这个类有七个主要的静态方法setCurrentTimeMillis、uptimeMillis()、 elapsedRealtime()、currentThreadTimeMillis、currentThreadTimeMicro、currentTimeMicro、sleep。
我们来看一下这两个函数的实际含义,以下是源码中的注释
/**
* Sets the current wall time, in milliseconds. Requires the calling
* process to have appropriate permissions.
* @return if the clock was successfully set to the specified time.
*/
native public static boolean setCurrentTimeMillis(long millis);
* Returns milliseconds since boot, not counting time spent in deep sleep.
* <b>Note:</b> This value may get reset occasionally (before it would
* otherwise wrap around).
* @return milliseconds of non-sleep uptime since boot.
*/
native public static long uptimeMillis();
/**
* Returns milliseconds since boot, including time spent in sleep.
* @return elapsed milliseconds since boot.
*/
native public static long elapsedRealtime();
/**
* Returns milliseconds running in the current thread.
* @return elapsed milliseconds in the thread
*/
public static native long currentThreadTimeMillis();
/**
* Returns microseconds running in the current thread.
* @return elapsed microseconds in the thread
* @hide
*/
public static native long currentThreadTimeMicro();
/**
* Returns current wall time in microseconds.
* @return elapsed microseconds in wall time
* @hide
*/
public static native long currentTimeMicro();
由此可见,
setCurrentTimeMillis(long millis)是用来设置系统时针,可参考 http://blog.csdn.net/cuijian2b/article/details/8034884
uptimeMillis()返回的是系统从启动到当前处于非休眠期的时间。
elapsedRealTime()返回的是系统从启动到现在的时间。
currentThreadTimeMillis()是在当前线程中已运行的时间。(milliseconds毫秒)
currentThreadTimeMicro()是在当前线程中已运行的时间。(microseconds微秒)
currentTimeMicro() 是获得当前系统的时间
还有一个方法 public static void sleep(long ms),和Thread.sleep的差别在于:
- Thread.sleep()是java提供的函数。在调用该函数的过程中可能会发生InterruptedException异常。
- SystemClock.sleep()是android提供的函数。在调用该函数的过程中不会发生InterruptedException异常,中断事件将要被延迟直到下一个中断事件。Use this function for delays if you do not use
Thread.interrupt()
, as it will preserve the interrupted state of the thread.