Timertask or Handler

Handler is better than TimerTask.

The Java TimerTask and the Android Handler both allow you to schedule delayed and repeated tasks on background threads. However, the literature overwhelmingly recommends using Handler over TimerTask in Android (see here, here, here, here, here, and here).

Some of reported problems with TimerTask include:

  • Can’t update the UI thread
  • Memory leaks
  • Unreliable (doesn’t always work)
  • Long running tasks can interfere with the next scheduled event

Example

The best source for all kinds of Android examples that I have seen is at Codepath. Here is a Handler example from there for a repeating task.

// Create the Handler object (on the main thread by default)
Handler handler = new Handler();
// Define the code block to be executed
private Runnable runnableCode = new Runnable() {
    @Override
    public void run() {
      // Do something here on the main thread
      Log.d("Handlers", "Called on main thread");
      // Repeat this the same runnable code block again another 2 seconds
      handler.postDelayed(runnableCode, 2000);
    }
};
// Start the initial runnable task by posting through the handler
handler.post(runnableCode);

Related

Leave a Comment