Interview Question

Interview Boston, MA

What are the various ways an Android developer can apply

  multi-threading to their app? Be specific, and give examples.

Interview Answer

1 Answer


since Android uses the Java language it provides all the normal threading mechanisms as all Java-based implementations. You create a Thread by either (a) sub-classing the Thread class with your own and over-loading the run() method to perform your background task, or (b) you create an instance of the Thread class by giving it an instance of the Runnable interface, and overload the run() method of that interface to perform your background task. Option (b) is preferred by far in most circumstances. Android, however, provides additional threading mechanisms over and above those provided by Java, and they tend to resolve some of the most interesting dilemmas in Java programming. In Android you have the following additional mechanisms: 1) AsyncTask 2) Handler 3) runOnUiThread() 4) IntentService (for Service implementations) So, depending upon what your needs are, you can greatly simplify your code by opting for the use of one of these mechanisms. For instance, the AsyncTask class provides a very nice encapsulation of creating a Java Thread, providing thread-correct calls for pre/post processing, and automatically uses a thread pool behind the scenes to efficiently use thread resources. All this and provides a very simple 4 method sub-classing interface where you can write just your background code within a single method, and the AsyncTask class will handle cross-thread messaging for you. You have to know, however, that AsyncTask uses a Handler instance internally, so if you're launching this from a Thread that doesn't use a MessageQueue, then this may not work properly for you. runOnUiThread() does just what it says, it will take a Runnable instance, and run it in the thread space of the main, or "UI", thread in Android. This is a handy feature when you just want a simple means of interacting with the user interface. Although specific to Service implementations, which should always be threaded, the IntentService provides automatic single-threading for simple implementations, saving tons of code the Service developer. Moral of the story? Read up on what's available in Android, and find the most elegant solution, rather than simply using the tired old Thread implementations we're so accustomed to.

Interview Candidate on May 10, 2012

Add Answers or Comments

To comment on this, Sign In or Sign Up.