AsyncTask: Playing with Threads.

Dhruvam Sharma
AndroidPub
Published in
5 min readMay 21, 2018
Pun Intended. Source.

Hi everyone. I am Dhruvam and I am here today to understand, along with you, what is AsyncTask all about and how it works. I know there are thousands and thousands of articles about it but today I’ll focus on the details of AsyncTask and tell you about it like I would to a 5 year old. In my past years I have faced difficulty in explaining Asynctask and Asynchronous behavior on numerous occasions so this is my attempt to help new developers understand it and experienced developers to refresh their mind with the gnarly details of it.

What are we going to learn here:

  1. What is Multi-Threading and UI Thread?
  2. Why to have a Multi-Threading Environment?
  3. What is AsyncTask and How does it works?

This is going to be a 2 part series. This part is going to be all about explanation and the next part will be all about implementation.

1. What is Multi-Threading and UI Thread?

UI thread is the main execution thread of any android application and all the application components like Activity, Services, Broadcast Receivers, Content Provider. Don’t get it? Read it here first.

When you explicitly spawn a new thread to do work in the background, this code is not run on the UIThread. So what happens if this background thread needs to do something that changes the UI? This is what the runOnUiThread is for. Actually you're supposed to use a Handler (see the link below for more info on this). It provides these background threads the ability to execute code that can modify the UI. They do this by putting the UI-modifying code in a Runnable object and passing it to the runOnUiThread method. Read it about here.

2. Why to have a Multi-Threading Environment?

Let’s suppose a restaurant “A” with just one cook to do all of the work, from taking orders to preparing food to cleaning the tables. All of the work pinned onto the cook.
The cook cleans the table first, then cut the vegetables, then prepare the food and then serve it and then cycle repeats again. If any of the task takes a longer time than usual, the customer would lash out and go.

Now let’s assume another restaurant “B” with 10 cooks, 1 manager, 10 cleaners, 10 waiters. All of them have different work assigned and they all work in a zig-zag manner. They all work at different times and report to the Manager after their work has been done. And then manager will tell what to do next to all the staff in the restaurant.
This kind of a restaurant will have more chances to succeed as compared to the Restaurant “A”.

Restaurant A.

This is how Android devices work. The UI thread has so many tasks to perform. Building and showing components on screen with 60 fps is a huge task in itself. And pretty fast! This is why if we ask the UI thread to work on things like making network calls and fetching data from the database or more complicated stuff, UI thread will explode!

Not explode exactly! Don’t take the words in literal sense! What will happen is that the screen will start lagging and the OS will show a dialog box saying: The app is not responding.

Image result for app not responding
Source

This is why Android provides us with the concept of threads and background tasks.

3. What is AsyncTask and How does it works?

AsyncTask is a wrapper class provided by android to perform all the heavy duty tasks in the background and relieve your main UI thread from this burden.

An AsyncTask starts on the UI thread and push all the heavy tasks like network calls, database calls etc, on the asyncTask class which starts a background thread. The background thread completes the task and return the results to the UI thread for modifying the UI if it has to be done. That’s easy right?

There is mainly 1 compulsory method to override from the AsyncTask class and that is doInBackground().

  1. doInBackgroud: This is the only method we need to override for running the AsyncTask. In this method we write the code for the heavy computations like downloading a file. Task that might take time will be added in this method of the AsyncTask. This method runs on the backgroud Thread.

There are 3 more methods that we can override in the AsyncTask. These are:

2. onPreExecute: This is the first method that runs when an asyncTask is executed. After this, doInBackground is executed. This method runs on the UI thread and is mainly used for instantiating the UI. Like showing the spinners while doing he background work.

3. onPostExecute: When the background task is done and executed, we need to send the results back to the UI thread. This method runs on the UI thread itself and all the results from doInBackgroud method is sent back to this method that is on the UI thread. See? How easy it made it for you to do the background work. All the work done for you. You did not handle the task of creating threads, runnable objects, handling the handler for the UI thread for receiving the results. So this is quite easy.

4. onPublishProgress: The timing of this method is undefined. It is executed on the UI thread and is used to update the UI for showing the progress of the background task at any given point. Example: Showing the progress bars while downloading a file.

See the image below and try to understand the details I just explained it to you. This is an exercise for you. If you still don’t get anything, please mention the problem i the comments below.

Source

If you’ve reached here, thank you so much for reading. Please clap and follow and show love ❤
#coding #android #love #udacity #google

--

--

Dhruvam Sharma
AndroidPub

Google-certified Android Developer @Unikon. Android Geek. In love with Flutter. Blockchain Explorer. Dancer. 🕺 Reader. Coffee Addict. 😍