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

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(){
@Override
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 : https://github.com/ankur-srivastava/HelloAndroid/blob/master/app/src/main/java/com/edocent/helloandroid/MainActivity.java

Author: androidsmartly

I am a Tech Enthusiast who likes to work on new Ideas. Sharing knowledge on Android, Marketing, Startups and More.

1 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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s