Posts Tagged ‘looper’

Android Guts: Intro to Loopers and Handlers

Thursday, June 3rd, 2010

One of the reasons I love Android API is because it contains so many useful little things. Many of them are not even specific to the platform and I really miss them in Java SE. Today I’d like to give a short introduction to two nice classes – Looper and Handler. They are used in Android UI internally, and available to us developers so we can do some cool things with their help.

So what can you do with Loopers and Handlers? Basically, they implement a common concurrency pattern that I call the Pipeline Thread. Here’s how it works:

  • The Pipeline Thread holds a queue of tasks which are just some units of work that can be executed or processed.
  • Other threads can safely push new tasks into the Pipeline Thread’s queue at any time.
  • The Pipeline Thread processes the queued tasks one after another. If there are no tasks queued, it blocks until a task appears in the queue.
  • Sometimes tasks can called messages and other names.

This architecture has some valuable traits and is widely used in frameworks and applications on different platforms.

In this post, we are going to build a simple app that emulates a queue of background downloads while showing its status in the UI. It will be based on a Pipeline Thread that we will build using Looper and Handler. As usual, the complete source is available at the bottom of the article.

(more…)