在AsyncTask doInBackground中调用Thread.sleep()需要比预期更长的时间

时间:2015-11-27 07:35:52

标签: android multithreading android-asynctask

我写了一个简单的AsyncTask:

    @Override
    protected Void doInBackground(Void... params) {
    for (int i = 0; i <= 99; i++) {
        long time = System.currentTimeMillis();
        try {
            //Wait for 6ms
            Thread.sleep(6);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long diff = System.currentTimeMillis() - time;
        Log.d(TAG, "Row "i + " is DONE with timeDiff=" + diff + "ms vs. waitTime=" + waitTime + "ms");
        publishProgress(i);
    }
}

在我试用LG设备(Nexus 4,G3)之前,它在一些测试设备中运行良好:睡眠时间似乎比我想象的要长。检查日志后,我看到正常情况下,timeDiff是6ms或7ms;对于LG设备,timeDiff主要是&gt; 40毫秒。

也尝试使用SystemClock.sleep(),但没有运气。

有人可以建议我如何解决它吗?任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

备用解决方案是使用Handler进行等待。

Handler handler = new Handler(); 
handler.postDelayed(new Runnable() { 
     public void run() { 
          //call after delay

     } 
}, 2000); 
相关问题