How to build a service-enabled Android app – Part 3/3 Multithreading
Posted June 4th, 2008 by Nazmul
We believe in the power of ONE, at ScreamingToaster.
We believe in innovation - ONE experience can change a person's life.
We believe in partnerships - ONE endeavor can establish lasting trust & mutual success.
We believe in education - ONE training course can empower a developer for life.
We believe in giving back - ONE open-source project can inspire future entrepreneur.
ONE person can become the leader that starts a revolution.
ONE company can change the world and make it a better place - join us.
Introduction
I’ve written 3 tutorials to show you how to create a service enabled Android application that performs all of it’s network I/O in a background thread (not the UI thread). Please note that by service I mean web-service, not Android Service. These tutorials are split into three parts:
- How to build a simple UI without using XML, by writing Java code to layout the UI.
- How to use Apache HTTP Client to connect to services over HTTP or HTTPS and exchange serialized Java objects with services.
- How to use background threads to perform long running network IO operations, so that the main UI thread is not locked up.
Android 101
To get started with Android, click here. Instead of reading the SDK docs to get the basics, I recommend that you read this book to get going.
Don’t hog the UI Thread
Just like with Swing, or any other single threaded GUI toolkit, in Android, you shouldn’t perform long running operations in the UI Thread. Imagine that there’s the equivalent of the EDT in Android, and it’s called the UI thread. There are also a UI thread utilities class, much like SwingUtilities for posting events on this UI thread.
Running tasks in the background thread
The basic structure of creating code that runs in a background thread is in the GetDataFromServlet class. If you’ve used SwingWorker before, you should see similarities.
Here’s what the first screen looks like:

Here’s the code that’s executed in the UI thread (called from the first screen) when the Login button is pressed:
public void execute(NetworkActivity activity) { _activity = activity; uid = activity.ttfUserid.getText().toString(); pwd = activity.ttfPassword.getText().toString(); // allows non-"edt" thread to be re-inserted into the "edt" queue final Handler uiThreadCallback = new Handler(); // performs rendering in the "edt" thread, after background operation is complete final Runnable runInUIThread = new Runnable() { public void run() { _showInUI(); } }; new Thread() { @Override public void run() { _doInBackgroundPost(); uiThreadCallback.post(runInUIThread); } }.start(); Toast.makeText(_activity, "Getting data from servlet", Toast.LENGTH_LONG).show(); }
Some notes on this code:
- Essentially a callback handler is created, which is activated when the task in the background thread completes. This callback handler is inserted into the event queue by using Handler.post(Runnable). This is similar to using SwingUtilities.invokeLater(Runnable). This callback handler has a method _showInUI() that will get invoked in the UI thread, when the background task completes.
- The long running task is performed in _doInBackgroundPost(). The UI thread just creates a new thread, and this new thread executes this method and calls the callback handler when it’s done. Any code in this method will run in the “background thread”, and not the UI thread.
- Once the background method is complete, the callback handler runs _showInUI() in the UI thread itself; so any code that goes in that method can block the UI. In this example, this code simply updates the 2nd screen with the Hashtable it downloaded, which is what it’s supposed to do.
- The calls to Toast are to display a simple status message that pops up and disappears on it’s own.
Here’s the code for _doInBackgroundPost():
/** this method is called in a non-"edt" thread */ private void _doInBackgroundPost() { Log.i(getClass().getSimpleName(), "background task - start"); Hashtable<String, String> map = new Hashtable(); map.put("uid", uid); map.put("pwd", pwd); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(map); PostMethod post = HttpUtils.sendMonitoredPOSTRequest(LoginServiceUri, null, new ByteBuffer(baos.toByteArray()), null); data = HttpUtils.getMonitoredResponse(null, post); ObjectInputStream ois = new ObjectInputStream(data.getInputStream()); dataFromServlet = (Hashtable<DataKeys, Serializable>) ois.readObject(); Log.i(getClass().getSimpleName(), "data size from servlet=" + data.toString()); Log.i(getClass().getSimpleName(), "data hashtable from servlet=" + dataFromServlet.toString()); } catch (Exception e) { ex = e; // Log.e(getClass().getSimpleName(), "problem encountered", e); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); Log.e(getClass().getSimpleName(), sw.getBuffer().toString(), e); } Log.i(getClass().getSimpleName(), "background task - end"); }
Here’s the code for _showInUI():
/** this method is called in the "edt" */ private void _showInUI() { if (data != null) Toast.makeText(_activity, "Got data from service: " + data.toString(), Toast.LENGTH_SHORT).show(); if (ex != null) Toast.makeText(_activity, ex.getMessage() == null ? "Error" : "Error - " + ex.getMessage(), Toast.LENGTH_SHORT).show(); // Toast.makeText(_activity, // "completed background task, rejoining \"edt\"", // _activity._displayUserProfile(dataFromServlet); }
Here’s a screenshot of the 2nd screen:

Download source code
To download the source code for this tutorial, click here. The source code comes with Eclipse projects, as well as IDEA projects, so if you have those IDEs you can get started pretty quickly. Once you unzip the file, you will find an “android” folder, this is the Eclipse workspace itself. If you look inside the “NetworkTest” folder, you will find the NetworkTest.ipr file, which is the idea project.
Comments, feedback
To share your thoughts on these tutorials, click here.
We do not just build mobile “apps”, we build mobile experiences
Let us build you mobile experiences for Android, BlackBerry, and iPhone. We can also build you cloud-connected experiences that span Mobile (Android, BlackBerry, iPhone), Web (Safari, Firefox, Internet Explorer) and Desktop (PC, Mac, Linux) for a truly connected real-time experience. See our work in action: download RainOrShine for BlackBerry and CityRyde for Android.
- We provide full service, full lifecycle consulting services (planning, graphic design, architecture, marketing, support, and implementation).
- We provide Architecture guidance before implementation; marketing strategy after implementation. Click here to learn more.
Zen Application Framework
All our applications are built using our Zen Application Framework, which helps you avoid the common pitfalls around mobile development. Zen drastically reduces development time & cost for mobile, web, and desktop experiences. Click here to learn more.
Our training services make You self-sufficient & sustainable
Want to learn from the best? We offer Android and BlackBerry developer training programs. Whether you are just starting out, or want advanced training, we have courses for different skill levels & technology requirements. Contact us to learn more, and sign up.
Our values: Open-source. Democratization of knowledge. To lead, never follow
We are leaders in mobile technology. We have done and seen it all. We do not follow trends set by others & we do not make the mistakes made by others. We set the trends for mobile because we are mobile visionaries.