前言
项目中,由于需要做防爆力点击,需要计算用户点击的时间间隔。
虽然也经常使用,但偶尔还是忘了该用哪个,以及这两个之间的区别,因此,抽空整理一下,摘抄于此。
Android中计算时间间隔的方法
记录开始时间 startTime,然后每次回调时,获取当前时间 currentTime,计算差值 = currentTime – startTime,而获取当前时间间隔
总结
- SystemClock.uptimeMillis() 从开机到现在的毫秒数(手机睡眠的时间不包括在内
- System.currentTimeMillis() // 从1970年1月1日 UTC到现在的毫秒数
由于系统时间存在变化,因此我们在进行判断时间间隔时使用的是SystemClock.uptimeMillis()
下面是计算时间间隔的demo代码
long startTime = SystemClock.uptimeMillis(); // 开始执行某代码片段 long endTime = SystemClock.uptimeMillis(); //计算时间间隔 long interval = endTime - startTime;
正文
SystemClock.uptimeMillis()
/** * Returns milliseconds since boot, not counting time spent in deep sleep. * * @return milliseconds of non-sleep uptime since boot. */ @CriticalNative native public static long uptimeMillis();
注释说明了,是系统开机到现在的时间。
下面是网用总结的:
uptimeMillis()获取的时间表示系统开机到当前的时间总数,单位是毫秒,但是,当系统进入深度睡眠(CPU休眠、屏幕休眠、设备等待外部输入)时间就会停止,但是不会受到时钟缩放、空闲或者其他节能机制的影响。
System.currentTimeMillis()
/** * Returns the current time in milliseconds. Note that * while the unit of time of the return value is a millisecond, * the granularity of the value depends on the underlying * operating system and may be larger. For example, many * operating systems measure time in units of tens of * milliseconds. * * <p> See the description of the class <code>Date</code> for * a discussion of slight discrepancies that may arise between * "computer time" and coordinated universal time (UTC). * * @return the difference, measured in milliseconds, between * the current time and midnight, January 1, 1970 UTC. * @see java.util.Date */ public static native long currentTimeMillis();
currentTimeMillis()获取的是系统的时间。
这个不可以作为时间间隔判断,因为系统时间存在变化(比如时间同步了,用户改变了当前时间或者时区)
我们可以通过下面方式改变系统时间
SystemClock.setCurrentTimeMillis(long millis)
参考文章
© 版权声明