Thursday, March 19, 2009

Timer in Android ( The Better Way )

The usual Timer class is available in Android, but unless you are doing non-trivial stuff, its better to use Handler for scheduling task. Why? Well, Timer class introduces a new thread and while developing mobile application, you should really think twice (or more than that!) before using it.

So, how jobs can be scheduled using Handler class? There are two different approaches. First, You can ask it to send messages at some later time by using sendMessageAtTime(Message, long) or sendMessageDelayed(Message, long) , which then can be processed as shown in my previous post, effectively acting as a timer. Secondly, you can directly ask it to run some scheduled task by using postAtTime(Runnable, long) and postDelayed(Runnable, long).

The methods described here lets you schedule a single shot task. To repeat a scheduled task, you have to register it again to run for the next time. So, assuming that you want to repeat a task after one second delay, we can do something like this,


private Handler handler = new Handler();


private Runnable runnable = new Runnable() {

public void run() {

doStuff();

/*
* Now register it for running next time
*/


handler.postDelayed(this, 1000);
}


};

To stop a repeated task you can use removeCallbacks(Runnable r), which removes all pending Runnable r in the message queue.

4 comments:

Unknown said...

useful!

SE said...

Hi Siam,
Saved some api doc digging time. Thanks

Unknown said...

yeah! Very useful and clean :)

Necmettin ASLAN said...

thanks very much, this is really very useful for me