how to use postDelayed() correctly in android studio?
You're almost using postDelayed(Runnable, long)
correctly, but just not quite. Let's take a look at your Runnable.
final Runnable r = new Runnable() {
public void run() {
handler.postDelayed(this, 1000);
gameOver();
}
};
When we call r.run();
the first thing it's going to do is tell your handler
to run the very same Runnable after 1000 milliseconds, and then to call gameOver()
. What this will actually result in is your gameOver()
method being called twice: once right away, and a second time once the Handler is done waiting 1000 milliseconds.
Instead, you should change your Runnable to this:
final Runnable r = new Runnable() {
public void run() {
gameOver();
}
};
And call it like this:
handler.postDelayed(r, 1000);
Hope this helps.
Thread(Runnable {
// background work here ...
Handler(Looper.getMainLooper()).postDelayed(Runnable {
// Update UI here ...
}, 10000) // It will wait 10 sec before updating UI
}).start()
Below is the code that I use which works same as the accepted answer but is quite simple to write and understand.
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Write whatever to want to do after delay specified (1 sec)
Log.d("Handler", "Running Handler");
}
}, 1000);