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:
useful!
Hi Siam,
Saved some api doc digging time. Thanks
yeah! Very useful and clean :)
thanks very much, this is really very useful for me
Post a Comment