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 withHandlerdidn’t work. But I think I already know the answer: I probably have to use apostdifferent for eachsetProgressright?– Androiderson
Yeah, that’s right! 'Cause while yours
postoccupied the UI thread, did not leave thepostmade internally bysetProgressand added to the main thread run queue. The fivesetProgressthen were executed quickly and in sequence without giving time to notice it visually.– Piovezan