Time Delays

Android doesn’t have a simple “sleep” or “wait” function.

The Android user interface thread is constantly checking for new input, so you can’t tell it to stop everything and wait. The app would freeze, which provides a poor user experience. Android tries to prevent the programmer from being able to freeze the app like that.

But you can still create time delays in Android.

Asynchronous / Threads / Runinng Tasks in Background

Android needs to run the delay timer as a background task. A Runnable object is a background thread that can run a piece of code. A Handler object manages the Runnable.

Example:

Handler h = new Handler();
h.postDelayed(new Runnable() {
    @Override
    public void run() {
    	//Commands to be delayed go here!
        myText.setText("It's 2 seconds later.");
    }
}, 2000);

Change the number from 2000 to some other number of milliseconds to change the time delay.

Change the code inside the run() method to make a different commands run after a delay.

To type this stuff into Android Studio, start with this much:

Handler h = new Handler();
h.postDelayed(  );

Now type a comma and a number between the parentheses:

Handler h = new Handler();
h.postDelayed(  ,2000);

Next put your cursor in the parentheses, before the comma, and start typing “New Runnable.” When you see “Runnable in the autocomplete menu, hit enter:

When you hit Enter, it will create the structure for a Runnable with the run() method already in place:

Your cursor is now blinking inside the run() method, and you can type the commands that you want to run after the 2000 millisecond delay.

Where does this code go in my program?

Put it inside a method in your main activity.