10
I made a test app in which I would like to see a ProgressBar
updating by simulating a long-duration task. I initially tried using Handler
because after some research I saw that its use was recommended:
final int tempoDeEspera = 500;
new Handler().post(new Runnable() {
@Override
public void run() {
SystemClock.sleep(tempoDeEspera);
progressBar.setProgress(1);
SystemClock.sleep(tempoDeEspera);
progressBar.setProgress(2);
SystemClock.sleep(tempoDeEspera);
progressBar.setProgress(3);
SystemClock.sleep(tempoDeEspera);
progressBar.setProgress(4);
SystemClock.sleep(tempoDeEspera);
progressBar.setProgress(5);
}
});
But I only got the expected result using Thread
.
final int tempoDeEspera = 500;
new Thread(new Runnable() {
@Override
public void run() {
SystemClock.sleep(tempoDeEspera);
progressBar.setProgress(1);
SystemClock.sleep(tempoDeEspera);
progressBar.setProgress(2);
SystemClock.sleep(tempoDeEspera);
progressBar.setProgress(3);
SystemClock.sleep(tempoDeEspera);
progressBar.setProgress(4);
SystemClock.sleep(tempoDeEspera);
progressBar.setProgress(5);
}
}).start();
I would like to know the details of the two implementations and the situations in which each one should be used.
Nice answer! But my doubt is not about the concept of
MainThread
, this is pretty basic. What I’d like to know is why the version withHandler
didn’t work. But I think I already know the answer: I probably have to use apost
different for eachsetProgress
right?– Androiderson
Yeah, that’s right! 'Cause while yours
post
occupied the UI thread, did not leave thepost
made internally bysetProgress
and added to the main thread run queue. The fivesetProgress
then were executed quickly and in sequence without giving time to notice it visually.– Piovezan