Scheduling a Timer in Android

When it comes to scheduling a timer in Android, you have a few choices, some better than the others.

Using Java Timer

Java’s built-in java.util.Timer works fine in Android. However, the TimerTask is fired in a secondary thread. That means, you can not change the GUI from the task.

The example below fires a timer in 2 seconds.

Timer timer = new Timer();

timer.schedule(new TimerTask() {
    public void run() {
        //Called in a secondary thread.
        //GUI update not allowed.
}, 2000);

Using a Handler

If you intend to update the UI when the timer fires, use the Handler API. A handler executes a Runnable in the same thread that the handler was created in.

In the example below, we fire a timer in 2 seconds.

Handler handler = new Handler();

handler.postDelayed(new Runnable() {
    public void run() {
        //Called in the same thread as where the handler was created.
        //If the handler was created in main thread, then
        //we can safely update the GUI from here.
}, 2000);

If we create the handler from the main thread, we can update the GUI from the run() method. This is irrespective of what thread calls the postDelayed() method.

One thought on “Scheduling a Timer in Android

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 )

Google+ photo

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

Connecting to %s