Criss crossing multicolored strings

In Android applications, there’s always at least one main thread that executes the most important tasks in an app: handling user interaction, drawing pixels on the screen, and launching activities. This thread is called the UI Thread, or Main Thread. Because it’s handling the most crucial parts of an app, you never want to block the UI thread when you’re coding activities—it could cause your app to lag, skip, or crash. The more complicated the tasks get in an app, the more opportunities to block the main thread.

While the main thread is handled for you by the runtime environment, managing other tasks is up to you—and can get tricky. Fortunately, the Android SDK provides developers with a few tools for managing threads, including AsyncTask, which is designed to offload some of the app’s work from the main thread. Here’s a look at AsyncTask and why Android developers should be using this valuable tool.

More about the UI Thread

In the UI Thread commands are executed line by line, meaning a command line is not executed until the current thread is finished executing. All of our application’s components (Activities, Services, ContentProviders, BroadcastReceivers, etc.) are created within this thread, and any system calls made to those components are performed there as well.

However, that doesn’t mean that all the huge processes must be executed in the main thread. There’s a workaround for this that can improve your app’s performance and give users a much better experience: background threads. These threads are designed to handle any potentially long tasks that may hang your application. Typical examples of such tasks are network operations, which can involve unpredictable delays.

Why should you use background threads?

Users will tolerate some pauses, especially if you provide feedback that something is in progress, but a frozen application gives users no clue—and makes them more likely to close your app and use it less in the future.

When you don’t use background threads, all of the code of an Android application runs in the main thread, with every statement executed one after another. If you perform a long-lasting operation, e.g. accessing data from the Internet, the application blocks until the corresponding operation has finished. The user is left hanging while the operation runs, leading to a poor user experience. The solution? Run all potentially slow running operations asynchronously in the background thread—things like network, file, and database access, or complex calculations. This allows the app to perform long/background operations and show the results on the UI thread without having to manipulate threads.

The best way to perform such background tasks? AsyncTask.

AsyncTask

Android defines AsyncTask as “a class that extends the Object class to allow short operations to run asynchronously in the background.” With “doInBackground” and “onPostExecute,” Async can run tasks asynchronously on new threads.

Infographic of how AsyncTask works

Asynchronous tasks use:

  1. Params, parameters that are sent to the task upon execution.
  2. Progress, the progress units that are published during the background computation.
  3. Result, the results of the background computation.

When an asynchronous task is executed, the task goes through 4 steps:

  1. onPreExecute: a step used to set up the task
  2. doInBackground: a step used to perform the actual task
  3. onProgressUpdate: a step used to update the current progress status of the task that is being performed in doInBackground
  4. onPostExecute: once doInBackground finishes executing the task, this step delivers the result back to the main UI thread and stops the AsyncTask process

Example uses of AsyncTask

Want to give AsyncTask a try? Here’s an example of how to use this function.

class DoSomeTask extends AsyncTask{

@Override
protected void onPreExecute() {
//Setup precondition to execute some task
}

@Override
protected String doInBackground(String... params) {
//Do some task
publishProgress (1);
return "";
}

@Override
protected void onProgressUpdate(Integer... values) {
//Update the progress of current task
}

@Override
protected void onPostExecute(String s) {
//Show the result obtained from doInBackground
}
}

Android AsyncTask

Interested in learning more about AsyncTask and background threads? Check out these Android developer resources.

This story was submitted by freelancer Abinash Neupane and does not constitute the views or opinions of Upwork.

Ready to get started? Create an awesome job post that attracts the freelancers and skills you need for your project.