What if there was no AsyncTask in Android? — Android AsyncTask possible implementation

Rajat Khanna
5 min readJul 17, 2018

--

This article covers how can you go about creating from scratch you own AsyncTask for use in Android.

A few days back a friend(Prateek Sharma), asked me about how to go about implementing an Async Task in Android. I had no idea at that moment but honestly thought it was a great question. The question had been troubling me since a few days now and I actually wanted to learn how this can be done. I went through a few articles about Multithreading frameworks in Java. Below I will be explaining one possible way to make a simple asynchronous task executing framework like AsyncTask. Obviously there will be multiple ways to attain this and obviously there is also Google’s way to do it. I am listing the steps I followed below. If you have any confusion, please do ask.

The first 4 steps describe how to implement the Android frameworks AsyncTask in Android, fell free to skip it if you want to directly jump to the interesting part.

As the first step, we create a new initial empty activity project in Android. The task we want out async task to perform is to extract the json as text from the following API(of course, you can use your own api or any webpage as well): http://www.mocky.io/v2/5b49ac2b3100005a008bc03b. [Code]

In step two, add two buttons and a textview on the main activity. One which will call the Async Task implemented via Android’s framework and another which will call the async task class written on our own. [Code]

Main layout file for the self implemented Async Task Project.

In the third step we will quickly add the AsyncTask given by the Android framework to our project. Also implement the onClickListener for the button on the view to run the async task. We also check that the respective functions are indeed run on the main and the background threads as promised by Android. [Code]

Android AsyncTask implementation.
Add OnClickListener for the android async task.

In the fourth step, we use the HttpURLConnection class to get the response from the API also, please don’t forget to add the internet permission to the project as well for the api to work. You should see the following response when you click the button. [Code]

AndroidAsync task with the url downloading job.
Change the parameters for the android’s AsyncTask being called from the MainActivity.
Add the internet permission to the Manifest file as well.

With the fifth step comes the interesting part, this is where we will start coding our own AsyncTask Framework. Lets start out be building our own Executors, we will require a background executor to run code on background threads and main thread executor to run our code on the main thread. Lets first add the MainThreadExecutor. The MainThreadExecutor will run tasks in the main thread or ui thread of android. We will create a new Handler and push the runnable to the message queue of the main thread of the app. [Code]

MainThreadExecutor to run tasks on the main thread.

In the sixth step, we provide a thread factory which will provide threads to the thread pool we will build next. [Code]

The thread factory required for Background Thread Executor.

In step 7, we implement the executor provider class which provides us with different executors. The number of threads we create in our thread pool is also dependent on the number of cores in our phone. Please note that this is a singleton as we don’t want more than one instance of this class at anytime. [Code]

Implementation of the ExecutorProvider.

In the eighth step, we create the final class or our main framework class that is MyAsyncTask class. Firstly lets just implement the basic structure of the AsyncTask. It has to have all three abstract functions, and the execute function. Also, that class itself has to be abstract. Here is what I came up with for my first iteration. [Code]

Basic structure of gonna be AsyncTask.

As the 9th step, for implementation I just wanted for now for all three functions to run one after another. This is obviously not possible with what I tried first as all three functions used to execute simultaneously. [Code]

MyAsyncTask failed try.
MyAsyncTaskImpl empty implementation structure.
Adding onClickListener for my implementation of AsyncTask.

Therefore after some consideration, I came up with another approach, I ran the onPreExecute directly, doInBackground as a callable so that I can wait for its execution to complete and then onPostExecute. This at least helped me attain the order of execution. Please note that I also created a MyAsyncTask implementation here as I has to test it. [Code]

MyAsyncTask changed to make it work in the correct order.

In the 10th step, even though this is good progress, it ain’t the solution. We still need to pass the solution from the background thread to the main thread. Also, we need to make it generic (wink, wink) in order to pass any kind of result class from background thread to main thread. Therefore, we add an generic argument to the abstract AsyncTask Class and also changed the return type of do in background and input parameters of the onPostExecute function to provide that return type. In the execute function, we changed the type to be returned by the callable of to the generic type provided by the user. and we passed that back by calling the onPostExecute. The implementation class was also changed just enough to be in compliance with the MyAsyncTask class. [Code]

MyAsync task added generic type
MyAsyncTaskImpl empty implementation to make it complaint with new generic type MyAsyncTask.

In final step, we modify the code in the MyAsyncTask implementation class to use MyAsyncTask class for running its background operations. Do note that the implementation classes of both the AsyncTasks to be similar. [Code]

MyAsyncTaskImpl with url task implementation.
Add parameters to implementation of AsyncTask.

P.S. : An unnecessary null check was being performed for the executors, which was removed in the last commit. [Code]

So, in this short post, I just presented one way in which one can implement AsyncTask. Obviously, we can make it much more smartly if use a lot of other features of Java Multithreading like Future Tasks. We will also have to take care of a lot of other edge cases which we have not considered right now. I would also like to give a shout out to Mindorks whose posts I referenced extensively while doing this short experiment.

I will soon try to add more features in this class like onProgressUpdate or maybe optimize it in a better way. Studying the Android AsyncTask class makes you realize the amount of thinking that goes into making something that simple we use (or used to) regularly in Android.

If you know of a better framework to solve this problem or have any other feedback, please do share. Also, I am am also learning while writing these posts so please excuse me if there are grammatical mistakes. Lastly, fell free to follow me on LinkedIn or twitter.

--

--