Android Basics – Using Handler and Runnable to Schedule Code

You will Learn about

  • Handler
  • post method
  • postDelayed method
  • Main Thread

Android runs every App in a separate Process for Security and Scalability.

So when you Run your App Android starts a Thread for the same.

A New Thread

Now if you want to run code which needs to run in the background then its recommended to use a separate thread for doing that.

This will not only improve user experience but also prevent delays and crashes.


Handlers can be used to Schedule code to run at a future time. Lets take an example.

Suppose you want your App to display a message a the user after 5 seconds, like “Do you need any Help ?”. Handlers can help us achieve this.

By using post and postDelayed methods. Post method can be used to start a code immediately. While using postDelayed you can delay the code execution.

Lets look at an example. I have created a method sayHello() to display a message to the user after 5 seconds. We will specify this in milliseconds.

I will be calling this method from the onCreate() in the MainActivity.

public void sayHello(){
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
public void run(){
Toast.makeText(MainActivity.this, “Do you need any Help ?”, Toast.LENGTH_SHORT).show();
}, 5000);

As you can see this code will help you delay the code execution by 5000 milliseconds. Cool, isn’t it !!

Code :

Author: Ankur

I am Enthusiastic about Learning new things and sharing my Knowledge. I like programming and have a pretty good background in Computer Science.

One thought on “Android Basics – Using Handler and Runnable to Schedule Code”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: