In this article, I’m going to cover almost everything that you need to know about Android AsyncTask class. So basically, AsyncTask is an abstract class which gives us the ability to perform heavy operations in the background and keeps the UI thread free.

For example: downloading a file from the internet or performing a short period of heavy operations.

Essentially in Android, whatever code we write in our Activity classes those are actually performed by our MainThread. So if you are performing any heavy work in the MainThread, your UI thread or MainThread will be frozen. Though sometimes you may have seen some crash issues. Therefore, the AsyncTask is the most important topic to learn. However, it’s a pretty straight forward to use in any Applications.



AsyncTask Essential Methods

Now just remember! These below methods can be used in order to execute and update UI from our Background Task.

Method NameDescription
onPreExecute()This method gets called before doInBackground() method gets called.
Typically this method is used to initialize some variables or some basic
setup that needs to be done before executing our heavy task!
doInBackground()In this method, you have written all the code which needs to be executed in
the background. Also from this method, we can communicate with our UI
thread in order to update the results that how much processing has been
completed!
onProgressUpdate()This method is basically needed to update the UI thread, just to notify
background processing which receives from doInBackground() method.
onPostExecute()This is the final method which is called after doInBackground() method
completes executing. Therefore you can update your UI with a final
result.


AsyncTask Params

In the below Figure B, you can get some idea about AsyncTask Params and the purpose of each individual param.

Figure B. AsuyncTask Parameters

As we can see above, in Figure B we have three datatypes and our first data type is used to pass through doInBackground method’s parameter which is a String type data. Also remember it can take an Array of string or any type of array list according to the requirements.

Our second data type is an Integer as shown in Figure B, used to update the progress of the background task. For example, if we have a File Downloader App and we want to update the UI. Say for an example of how much byte needs to be download or to know the remaining size. In such cases, we should take Integer as in the second parameter.

The third data type is used to get the final results, which is actually the return type of our doInBackground method which also used in onPostExecute method’s parameter.



Anonymous AsyncTask

All right! This below anonymous AsyncTask is actually implemented inside an onCreate method of MainActivity.java, just to keep it simple. And inside that anonymous class, we have only one method called doInBackground.

new AsyncTask<string, integer,="" string="">() {
            @Override
            protected String doInBackground(String... strings) {
                return null;
            }
        }.execute();

Although we can override our rest of three methods onPreExecute, onPostExecute and onUpdateProgress inside that. But this is not the best practice to work with our AsyncTask or BackgroundTask class.

Now you may ask yourself! that what are the best practices to implement the AsyncTask?




AsyncTask Best Practices & Implementation

Essentially you can create an inner class then simply extends the AsyncTask Class as shown in below code snippets. So that we can get access to any variables or objects from our Activity or from any classes to the AsyncTask extended class. Although it is not necessary to have an inner class only, we can also create a Java class file and then simply extend the class.

But remember if we create a java class file instead of an inner class, in such a situation we should have to create an interface also, in order to update our UI.

private class DownloadTask extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Do some initialization staffs
        }

        @Override
        protected String doInBackground(String... strings) {
            // Write here your heavy Network Operations or any complex logic
            // updateProgress(fileSize);
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            // Update your BackgroundTask's Progress
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(s);
            // Update your UI with final data or result
        }
    }


Calling the AsyncTask Class

Now in order to execute or call the above class from our MainActivity’s onCreate method or maybe from a button onClick method, we just need to follow the below code snippet.

DownloadTask downloadTask = new DownloadTask();
downloadTask.execute("PASS_YOUR_URL");   
     
//OR
new downloadTask.execute("PASS_YOUR_URL"); 

Remember: calling execute() method and passing one URL instead we can pass multiple URLs such as url1, url2, url3, …



DownloadTask downloadTask = new DownloadTask();
        
        String[] urls = {"www.dailycoding.in/image00.png", 
                "www.dailycoding.in/my_ducument.pdf", 
                "www.dailycoding.in/video.mp4"};
        
        downloadTask.execute(urls);

As we can see in the above code snippets, we have passed a list of URLs through execute method call. Therefore that list should be extracted in the doInBackground method, as shown in the below code snippets. And our task will be in the RUNNING state until it reaches the final URL.

 @Override
        protected String doInBackground(String... strings) {
 for (int x = 0; x < strings.length; x++) {
                String url = strings[x];
                // Once we receive the url we can start downloading ..
            }
            return null;
        }


AsyncTask Status

There are a total of three constants available in this class RUNNING, PENDING and FINISHED. As shown in below code snippets, we can call the getStatus method in order to get the current status of the Background task.

public void downloadButtonClick(View view) {
        DownloadTask downloadTask = new DownloadTask();

        if (!downloadTask.getStatus().equals(AsyncTask.Status.RUNNING))
           downloadTask.execute("YOUR_URL");
        else
            Toast.makeText(this, "RUNNING", Toast.LENGTH_SHORT).show();
    }

Remember: Before we execute any background task we should check the Status.



That’s it. I hope now you can implement AsyncTask class in your Android applications. For more guidance on this topic, click here to explore an example base on today’s discussion.

References:

Google Docs

Translate »