How to use handler as a timer in android?
23,915
Solution 1
Handler.postDelayed
returns immediately. And next line is executed.
After indicated milliseconds, the Runnable
will be executed.
So your code should be like this:
void doFirstWork() {
Handler handler = new Handler();
if (v.getId() == R.id.play){
handler.postDelayed(new Runnable() {
public void run() {
play.setText("Play");
doNextWork();
}
}, 2000);
play.setBackgroundResource(R.drawable.ilk);
}
}
void doNextWork() {
...
}
Solution 2
Set the background first. After that set the text within Handler. As you've put delays at the end of postDelayed so it'll fire right after that stated delays or in your case after 2 sec.
if (v.getId() == R.id.play){
play.setBackgroundResource(R.drawable.ilk);
new Handler().postDelayed(new Runnable() {
public void run() {
play.setText("Play");
}
}, 2000);
}
Author by
Enes
Updated on August 10, 2020Comments
-
Enes almost 4 years
Handler handler = new Handler(); if (v.getId() == R.id.play){ handler.postDelayed(new Runnable() { public void run() { play.setBackgroundResource(R.drawable.ilk); } }, 2000); play.setText("Play"); }
I want to set background first and then after 2 seconds later, code will continue next line which is
play.setText("Play");
and goes like that. Instead of this, first text appears. 2 seconds later background changes. -
Enes almost 8 yearsOk. I got this but what I want is that after Handler.postDelayed is executed, the code will continue next line because there are many code blocks in there. Is there any method like that?
-
nshmura almost 8 yearsI updated my answer. Blocking UI Thread is unti-pattern in Android development. If you block the UI Thread, users will frustrated. .