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.

Leave a Comment