Living in an Internet-driven world, mobile apps need to share and receive information from their product backends (for example, from databases) as well as from third-party sources like Facebook and Twitter. These interactions are often done through RESTful apis. As the number of requests increases, the way they are initiated becomes more important to the development department, because how you get data can really affect the user experience of an application.

In this article I want to share some of my experiences with web libraries in Android development from the API level. I’ll start with basic synchronous and asynchronous programming and cover the complexities of Android threading. Then we’ll dive into the AsyncTask module, understand its architectural flow and read sample code to see how it is implemented. I’ll also talk about the limitations of the AsyncTask library and introduce you to Android Volley, which can be a better way to make asynchronous network calls. We’ll then take a closer look at Volley’s architecture and use code examples to show you some of its valuable features.

Can you keep your spirits up at this point? Figuring out how to program the Android Web can make you an experienced app developer.

Note: There are other Android libraries with web development capabilities that are not covered in this article, including Retrofit and OkHttp. I suggest you get to know them by yourself.

Read the following articles at SMASHINGMAG: 

  • What Every App Developer Should Know about Android

  • Android Mobile Design Practices: Tips and Techniques

  • Introduction to Android Development with Eclipse

  • How to Design for Android

The programming approach is simply synchronous and asynchronous

“Wait, mom, I’m coming.” Jason said this, still sitting on the couch, waiting to hear back from his girlfriend, whom he had called an hour earlier. “You should clean your room while you’re waiting to hear from your girlfriend.” Jason’s mother responded sarcastically. Isn’t her suggestion obvious? This scenario is similar to that of synchronous and asynchronous HTTP requests. Let’s take a look.

Synchronous requests behave like Jason and wait until a response is sent from the server. Synchronous requests can clog the interface, increase computation time, and make the application unresponsive (not always — sometimes it doesn’t make sense to stop waiting, such as for bank transactions). A smarter way is as Jason’s mom suggested. In the asynchronous world, when a client makes a request to a server, the server dispatches the request to an event handler, registers a callback, and then moves on to the next request. When there is a response, the client responds to the result. This is a better approach because asynchronous requests can be executed independently of each task.

Synchronous and asynchronous comparison (To view a larger version)

The figure above shows the difference between the two programming approaches in the client-server model. In Android, the UI thread is often referred to as the main thread, based on the same philosophy as synchronous programming.

Android thread

What are they and how do they work?

A thread is a collection of instructions managed by the operating system. Multiple threads run under a process (similar to Linux processes on Android) and share resources such as memory. In Android, when an application is running, the system creates a thread of execution for the entire application, called the “main” thread (or UI thread). The main thread works in a single-threaded model. It handles the dispatch of UI component (draw event) events, interacts with components through the UI toolset, such as view.onClickListener (), and responds to system events, such as onKeyLongPress().

The UI thread runs in a wireless loop and monitors the message queue to see if the UI needs to be updated. Let’s look at an example. But when a user touches a button, the UI thread sends the touch event to a component that can set its press state and send a request to the message queue. The UI thread pulls the request from the message queue and then tells the component to perform the action — in this scenario, the component redraws itself to indicate that the button was pressed. If you’re interested in learning more about UI threads, you should read about the Looper, MessageQueue, and Handler classes that perform the tasks discussed in our example. As you might expect, the UI thread has a number of responsibilities, such as:

  • Start an activity;

  • Execute a service;

  • Response to system callback.

Why can’t YOU block the UI thread

When you think about it, your single-threaded UI thread is doing all the work in response to user interaction. Because everything happens on the UI thread, time-consuming operations such as database queries and network calls can block the UI. The UI thread sends events to the UI component. When your app doesn’t perform well, users feel stuck. Android throws an “Application Not Responding” (ANR) error if the time taken for these tasks blocks the UI thread for four to five seconds. You can’t expect good reviews for an Android app that’s not very user friendly, and bad reviews and hasty uninstalls are likely to follow.

Using the main thread to handle long time consuming tasks can mess things up. If the UI thread is non-blocking, your application will always continue to respond to user events. This is why if your application needs to make a network call, the call needs to be executed on a worker thread running in the background, not the main thread. You can use a Java HTTP client library to send and receive data over the network, but the network call itself should be performed by a worker thread. Wait, there’s another issue in Android: thread safety.

Thread safety, and why it’s so important!

The Android UI toolset is non-thread-safe. If the worker thread (which performs the task of initiating network calls) updates the Android UI toolset, undefined and unexpected behavior can occur. Such problems are difficult and time-consuming to track down. The single-threaded model ensures that the UI is not modified by different threads at the same time. So, if we need to update the ImageView with an image from the network, the worker thread will perform the network operation in a separate thread, and the ImageView will be updated by the UI thread. This way, with the UI thread providing the necessary synchronization mechanism, you ensure that the operation is thread-safe. This also allows the UI thread to always remain non-blocking, since the actual work takes place in the background worker thread.

To sum up, there are two simple rules to follow in Android development:

  • Don’t block the UI thread.

  • The UI toolset cannot be updated directly through a worker thread that is not a UI thread.

A note about Android services

When it comes to making requests to an activity, you’ll encounter Android “services.” A service is an application component that can perform time-consuming operations in the background without requiring the application to handle the state of the activity, or even when the user has switched to another application. For example, services make it great to play music or download content in the background. If you choose to use a service, it will still run in the main thread by default, so you need to create a new thread in the service to handle blocking operations. If you need to perform operations outside of the main thread while the user is interacting with the application, it is best to use a network library such as AsyncTask or Volley.

It’s fine to perform tasks in a worker thread, but if your application starts to perform complex network operations, it can be difficult to maintain with a worker thread.

AsyncTask is a pit

It is now fairly clear that we should use a stable HTTP client library and make sure that network tasks are implemented in the background using worker threads — in other words, non-UI threads.

Android has a resource that can help you handle network calls asynchronously. AsyncTask is a module that allows us to perform asynchronous operations on a user interface.

What does asynchrony give us?

AsyncTask performs all blocking operations, such as network calls, in a worker thread and publishes the results after completion. The UI thread takes these results and updates the user interface accordingly.

Asynchronous tasks on Android (To view a larger version)

Here are the steps I took to implement an asynchronous worker thread using AsyncTask:

  1. Define a subclass of AsyncTask that implements the onPreExecute() method, which creates a message indicating that a network call is about to occur.

  2. Implement the doInBackground (Params…). Methods. As the name implies, doInBackground is the worker thread that makes the network call and protects the mainline from being free.

  3. Since the worker thread can’t update the UI directly, I implemented my own postExecute(Result) method, which passes the results from the network call operation and runs in the UI thread so that the user interface can be safely modified.

  4. The Progress of the background task can be published from the worker thread using the publishProgress() method and onProgressUpdate(Progress…). Method is updated on the UI thread. These methods are not implemented in the sample code, but are fairly straightforward to use.

  5. Finally, the asynchronous task is invoked from the UI thread using the execute() method.

Note that execute() and postExecute() both run on top of the UI thread, so doInBackground() is a non-UI worker thread.