【问题标题】:Android: what are the pros and cons of using a CountDownTimer vs Thread.sleep()?Android:使用 CountDownTimer 与 Thread.sleep() 的优缺点是什么?
【发布时间】:2017-07-26 09:13:04
【问题描述】:

我想做的事:

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

解决方案 #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();

我的问题

虽然两者都有效,但我想知道是否有“更好”或“首选”的方式来做这件事,无论出于何种原因。我认为可能存在一些领域,特别是在电池寿命方面,但在性能、准确性或代码设计方面,一种解决方案比另一种更好。

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

到目前为止,我对this SO questionCountDownTimerdocumentation 的评价是,由于两者都是在工作线程上执行的,因此两者都没有ANR 的可能性。这两种解决方案还将保证只有在上一次更新完成后才会发生一次“更新”。不幸的是,这就是我所拥有的一切,希望有人可以帮助或指导我解决我可能忽略或未能成功找到的有见地和/或类似的 SO 问题。

我写这个问题有点谨慎,因为我没有需要调试的有问题的代码,但我认为这属于“特定编程问题”的SO's 类别,尚未得到回答,也不包括在内在离题答案列表中。

【问题讨论】:

    标签: android multithreading countdowntimer


    【解决方案1】:
    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);
        }
    

    【讨论】:

      【解决方案2】:

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

      2.如果线程执行暂停,您将无法使用该特定线程进行任何其他操作,直到睡眠超时,因此不建议使用 Thread.sleep 方法。显然,如果它必须恢复线程执行并暂停它,则会对 cpu 造成负载。在倒数计时器的情况下,线程继续处于执行/空闲状态,并且当事件发生时,它会触发相应的侦听器。

      【讨论】:

        猜你喜欢
        • 2010-12-03
        • 1970-01-01
        • 1970-01-01
        • 2016-03-26
        • 1970-01-01
        • 1970-01-01
        • 2010-09-08
        • 1970-01-01
        • 2012-05-12
        相关资源
        最近更新 更多