Android:与 Thread.sleep() 相比,使用 CountDownTimer 的优缺点是什么?

Android: what are the pros and cons of using a CountDownTimer vs Thread.sleep()?

我想做的事情:

我想使用工作线程定期更新 UI 线程中的文本字段。比方说,每 2 秒一次,持续 30 秒。即使应用程序不在前台,我也需要 30 秒倒计时。目前,我正在评估两种不同方法(均使用工作线程)在实现时的优点。我不会在这里 post 完整代码来简化事情,也因为我不要求在我的代码中发现任何问题。两种解决方案都可以正常工作。

解决方案 #1 - 在 for 循环中使用 Thread.sleep()

for (int i = 30; i > 0; i-=2) {
    Message msg = mHandler.obtainMessage(MSG_ID, i, 0);
    msg.sendToTarget();

    try {
        Thread.sleep(2000);
    } catch(Throwable t) {
        // catch error
    }

}

解决方案#2 - 使用CountDownTimer

Looper.prepare()

new CountDownTimer(30000, 2000) {
    public void onTick(long millUntilFinish) {
        int seconds = (int)(millUntilFinish);
        Message msg = mHandler.obtainMessage(MSG_ID, seconds, 0);
        msg.sendToTarget();
    }

    public void onFinish() {
        // left blank for now
    }
}.start();

Looper.loop();

我的问题

虽然两者都有效,但我想知道无论出于何种原因,是否有 "better" 或 "preferred" 方法来做到这一点。我认为可能存在一些领域,特别是在电池寿命方面,但在性能、准确性或代码设计方面,一种解决方案优于另一种解决方案。

到目前为止我为回答这个问题做了什么

到目前为止,我自己的评价是 and CountDownTimer's documentation 因为两者都是在工作线程上执行的,所以都没有 ANR 的可能性。这两种解决方案还将保证 "update" 只有在上一次更新完成后才会发生。不幸的是,这就是我所拥有的,希望是否有人可以帮助或指导我提出一个有见地的 and/or 类似的 SO 问题,我可能忽略了或没有找到。

我写这个问题有点谨慎,因为我没有需要调试的有问题的代码,但我认为这属于 "specific programming problem" 的 SO's 类别,尚未得到解答, 并且不包含在题外答案列表中。

call Thread.sleep() method is not good idea beacuse ii sleep the UI Thread and disadvantage of  CountDownTimer is, It Will stop when ur screen is off hence instead of this two try  Handler for that like this


 Handler handler;
    Runnable runnable;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        handler = new Handler();
        Runnable runnable = new Runnable() {
            @Override
            public void run()
            {
                if (dataReceived)
                {
                    cancelHandler();
                }
            }
        };
        handler.postDelayed(runnable, 100);
    }

    public void cancelHandler()
    {
        handler.removeCallbacks(runnable);
    }

1.Calling Thread.sleep 暂停线程执行一段时间,因为倒数计时器实际上使用回调来通知计时器到期事件并且本质上是异步的。

2.If 线程执行暂停,在睡眠超时之前您将无法使用该特定线程进行任何其他操作,因此不建议使用 Thread.sleep 方法。显然,如果它必须恢复线程执行并暂停 it.Where,cpu 就会有负载,因为在倒数计时器的情况下,线程继续处于 execution/idle 状态,并且当事件发生时它会触发相应的听众。