Async Task

AsyncTask is an abstract class which means that the class extending it need to implement the below mentioned methods and also since the class is generic type the class extending it should specify these 3 generic types.These are explained below:-

private class SomeTask extends AsyncTask{

1. onPreExecute() –> This method is invoked just before the background thread is created and here we can do some initialisation that we might want to do before the background thread starts the task.
It is used to basically setup a task. Ex: showing a Progress Bar,etc.
It runs on the main UI thread.
2. doInBackground(Params…) –> This method is invoked on the background thread immediately after onPreExecute has finished executing and is used to perform the task which is supposed to be run on the background thread.This method can also call publishProgress(Progress…) method to puclish progress on the main UI thread which is received by the onProgressUpdate(Progress…) method.
Ex: Fetching results from a network request, etc.
It runs on the background thread.
3. publishProgress() –> This method can optionally be called within the doInBackground() method to publish progress to the main UI thread and show that progress to the user.
It can be called several times within the doInBackground to keep the user updated about the progress of the task happening.
4. onProgressUpdate(Progress…) –> This method is invoked on the main UI thread just after publishProgress(Progress…) is invoked on the background thread and it receives the current progress and can used to display/update the progress on the main UI.
It runs on the main UI thread.
5. onPostExecute(Result) –> This method is invoked on the main UI thread just after the background thread has finished executing and has returned the result to this method as seen in the method parameter. The result can be then be used to do anything the developer wants to do with that result.
It runs on the main UI thread.

AsyncTask’s Generic Types:-

Params → The type of parameters sent to the background thread to be used upon execution.
Progress → The progress which is used to publish the progress on the main UI thread.
Result → The result which is obtained after the background thread has finished execution.
AsyncTask is basically used to reduce the load of tasks off the UI thread. It creates a background thread to perform an operation like that of fetching results from the Internet or loading data from the database, etc. and then publish the results to the main UI thread.

private class DataFetcher extends AsyncTask{
protected void onPreExecute() {
//Used to show the progress bar

protected void onPostExecute(Integer result) {

protected String doInBackground(String… params) {
// Here the code to execute something on the background
// thread is written. May call publishProgress() to publish
// progress to the main UI thread.
//Finally after finishing the task return the result in the
//form of an Integer
new DataFetcher.execute(someStringVariable)

String is used to tell that the input data is of type String.
Void is used to tell that we do not want to publish the progress on the main UI thread.
Integer is used to tell that the result will be in the form of an Integer.

Why AsyncTask…?
If our app deals with the data loading from the internet or over a network or doing any other task which can take time and you are using the main thread to execute the operations of that task then it introduces a lot of load on the main UI thread.Let me explain this…

In normal scenerio your data will load in almost no time and the user doesn’t notice a difference but if the user is in an area where there is a slow internet connection then the task which is executing on the main UI thread will take longer than expected to respond and hence the user cannot further interact with the app since the main UI thread is busy fetching the results and cannot perform other tasks. Therefore, AsyncTask came into existence so that the load of doing such things is reduced on the main UI thread and pushed to a background thread so that even if it takes slightly longer to fetch the results, the app will be able to respond to user clicks and the user can freely interact with the app. When the task is completed then the result is published to the main UI thread by calling onPostExecute() asynchronously which in turn, displays the result/uses that result to do something.

Why should AsyncTask be used ideally for small operations…?
As you may have seen that 3 methods in AsyncTask run on the main UI thread and only two(including the publishProgress( )) method run on the background thread. This type of working can block the main UI thread even though the task to be performed is being done in the background. Let me explain this:-

If your app is loading something from the internet through a network request where the area in which the smartphone is being used has a slow internet connection due to any reason and your user presses the refresh button then another AsyncTask will be created and the methods of that AsyncTask would also run on the main thread but they won’t be able to run it since there is already an AsyncTask running and the onPreExecute() method of the second AsyncTask will not be invoked on the main thread until the previous AsyncTask is done with it’s work and onPostExecute() is called, hence blocking all other methods in the application used to respond to user clicks or any other functionality, hence freezing the app.

If you want to perform long operations in the background then you can use other classes like Executor,ThreadPoolExecutor and FutureTask.
The main disadvantage of using an AsyncTask and why they should rarely be used…
Block the main UI thread → One reason for this is the same as mentioned above that it can block the UI thread thereby freezing the app.
Wastage of memory →The creation of another AsyncTask can not only happen through refresh button but a rather more general and practical example is suppose an AsyncTask is already running and the user rotates the screen, then another Activity will created and the former activity will go to the Stopped State and since there is a completely new Activity a new AsyncTask is created and a new background thread is created and then suppose the user again rotates the screen before the task is completed, then another AsyncTask is created with a new background thread, and it can happen again and again creating multiple number of AsyncTasks in the memory thereby creating a large number of AsyncTask objects is created in the memory which in turn, wastes a lot of memory and since memory is a very precious resource in Android and should be used as efficiently as possible, it is not at all recommended. And if this scenario happens again & again than Android OS will have no coice but to forcefully destroy your Activity which you definitely do not want to happen.
Can lead to Memory Leaks → If the user rotates the screen another AsyncTask is created and as you know that the previous AsyncTask did not finish executing. Now, after the 1st AsyncTask completes with the 2nd Activity in the foreground then that AsyncTask will try to return the result to the onPostExecute() method of an Activity which does not exist and hence it leads to memory leaks.
Therefore, based on the above scenarios, AsyncTask should very rarely be used or used only for small operations.
Due to the above reasons AsyncTask is very rarely used and instead of that a better way is used called the AsyncTaskLoaders.