Too many options for Android threads? Let me help!

July 28, 2011

As smartphones continue to gain popularity, the demand for mobile applications also continues to grow.  The increase in usage of smartphones elevated the issue of “multitasking” on mobile devices.  (I’m not going to go into details of my opinions on the myth and illusion of multitasking.)

Ultimately, users want to have multiple applications running, syncing data, and connecting to the internet.

One solution to meet this demand is to block the UI and potentially display progress.  This can be a problem because users who perceive an application to be slow, sluggish, or non-responsive will give your app poor reviews in the market.  A more ideal solution is to perform long running, slow, or blocking tasks in the background.  The same work is being done, but the UI is snappy, or responsive.  An added benefit is that you won’t end up having one of these gems while trying to get the latest news updates about the NFL Lockout…

Android has many options for performing background tasks.  Specifically, Android gives you the opportunity to define what process your component runs in, control threads, and communicate remotely with components and processes.  Great!  Let’s use this to make awesome applications.  What’s the name of this magical background task thingy?  Well, get ready, because there’s a list…

  • Process
  • Thread
  • Synchronized
  • Handler
  • Messenger
  • AsyncTask
  • Service
  • BoundServices
  • IntentServices

In theory, this is great!  However, there are so many options that it can be overwhelming.  And you can’t just start moving everything to a new thread, because multithreaded applications introduce new challenges, like…

  • What about concurrency?  Is that a problem? (That’s a rhetorical question.  Of course concurrency is an issue!)
  • Deadlock, livelock, and  starvation (“Oh my!”)
  • What do my users expect?  If I do things in the background, does that break the communication loop?
  • I’ve heard lifecycle is important, what does this mean?

In a series of posts, I’ll cover the options, explain possible approaches, and make recommendations on when to use which options. I will even put up some sample code to help illustrate my points.  Along the way, I will answer the above questions and more.  After all, you want to be sure that you’re using the right tool for the job, right?