我有几个计时器需要同时运行。我知道CountDownTimer在完成阶段[onFinish()]时会出现问题,该阶段有时会提前完成一些时间,但对彼此之间的优缺点却知之甚少。直接调用System.currentTimeMillis()必须轻一些,但是CountDownTimer除了具有易用性之外,还必须具有某种优势,不是吗?

例如,类似

long totalTime = 30000;
long startTime = System.currentTimeMillis();
long currTime = System.currentTimeMillis();
while(totalTime > startTime - currTime){
    currTime = System.currentTimeMillis();
}
System.out.println("Finished!");

最佳答案

CountDownTimer的主要优点是您在倒计时期间会收到常规通知。与主动调用System.currentTimeMillis()相比,这些通知提供了一种简单的方式来响应剩余时间,而主动调用CountDownTimer可能仍需要某种计时器机制。 CountDownTimer代表您执行计时器设置,回调和清除。

您的示例代码将使CPU非常繁忙(从而消耗更多的电池寿命),而没有任何好处。如果代码在主线程上运行,这还将使应用程序的UI无响应。另一方面,CountDownTimer不会使UI停滞,只会在执行通知时消耗CPU时间。从性能和易用性的角度来看,使用是正确的选择。

关于java - 与直接使用System.currentTimeMillis()相比,使用CountDownTimer()的任何优势,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18934948/

10-10 22:45