Home > Uncategorized > Android: Timer/TimerTask out, Handler in

Android: Timer/TimerTask out, Handler in

You have probably heard about Java’s Timer and TimerTask classes. If you haven’t yet, go and learn about them since they are very handy easpecially if you are working on an app (like me) which needs to continuosly update various values that are displayed on the screen. Of course there are more professional ways to achieve such a task like the MVC and Observer patterns but this is one quick and simple way to accomplish such a task.

Anyways, when writing some UI related code usually updating/modifying something in the UI thread from some other thread can be really painful if you are not careful. Generally, you need to tell the program to synchronize a task with the UI thread manually or by using some special functions. Some platforms provide functions for specific purposes such as Android’s AsyncTask which makes it easy to modify the UI thread from the Background thread (ex. progress bars).

In Android, a Handler is a great way to schedule execution of tasks at a later time like the Timer class. In addition to this it can be also used to execute taks on the UI thread without any problems. The basic idea is that it takes a Runnable as an argument and depending on the method it executes it once as specified. A sample usage is shown below:


Handler updateHandler = new Handler();

Runnable runnable = new Runnable(){

	public void run() {
		updateDisplay(); // some action(s)
	}
	
};

updateHandler.postDelayed(runnable, 5000);

However, Timers in Java are esepcially helpful when they are used together with a TimerTask (at least for my case). With a simple trick it is possible to make a Handler act like a TimerTask as shown below:



final Handler updateHandler = new Handler();

Runnable runnable = new Runnable(){

	public void run() {
		updateDisplay();
		updateHandler.postDelayed(this, 5000); // determines the execution interval
	}
	
};

updateHandler.postDelayed(runnable, 5000); // acts like the initial delay

As you can see, all you need to do is to simply invoke the Handler after your action(s) is/are executed which essentially gives you have a TimerTask with an initial delay and specified execution intervals that can safely execute UI related code.

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment