what I want to achieve is Upon click, app shows toasts message "TEXT1", and keeps showing TEXT1 until finish other function call 20 times at a random interval/delay. After calling function,shows toast message "TEXT2". My problem: TEXT1 does not show until app finishes function call. and TEXT1 keeps up for the time it takes to execute 20 times function call,then TEXT2 shows up.My code:
public void onClick(View v) {
switch (v.getId()) {
case R.id.example:
Toast.makeText(getBaseContext(),"Please wait until finish",Toast.LENGTH_SHORT).show();
int i = 0;
while (i <= 19 ){
int delay = new Random().nextInt(5000);
try {
Thread.sleep(delay);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
//some function here
i++;
}
Toast.makeText(getBaseContext(),"Finished",Toast.LENGTH_SHORT).show();
break;
}
}
}
All user interface operations are handled in the UI thread. If you block the UI thread with a Thread.sleep
call, an ANR (Application Not Responding) will occur. Moreover, Thread.sleep
is never the right way to create timers, unless you are writing the core heartbeat of a worker thread.
Instead, you should use Handler.postDelayed
:
public void onClick(View v) {
final Handler handler = new Handler();
final Random random = new Random();
Runnable runnable = new Runnable() {
private int count = 0;
@Override
public void run() {
count++;
if(count > 20) { // 20 times passed
Toast.makeText(getBaseContext(), "Finished", LENGTH_SHORT).show();
return;
}
Toast.makeText(getBaseContext(), "Please wait until finish", LENGTH_SHORT).show();
handler.postDelayed(this, random.nextInt(5000));
}
};
runnable.run();
}
Edit: the OP wanted to use something like this. https://gist.github.com/SOF3/07c3c110aa214fcdd752e95573b7076f
See also: