AsyncTask:
In Android, we have 2 types of threads.
1) UI/Main Thread
2) Worker/Background Thread
UI/Main Thread – This thread is responsible for all the UI related operations. All the View Hierarchy and its operations only on Main Thread. No other threads can touch View Hierarchy other than the UI/Main Thread.
Worker/Background Thread – This is a background thread, which is used for network-based operations, database related huge data operations to ensure the UI Thread is not blocked with lot of operations. We can create any number of background threads and do some operations. We use this thread to achieve parallel computing/processing. This thread cannot perform any UI operations. This can be started from the Main thread, finish its task and reports the result back to Main Thread.
To create a worker thread and get some task done and report back to the main thread,
we need to do a lot manual checks. It requires of lot of coding. To overcome this problem, we have AsyncTask in Android.
AsyncTask:
AsyncTask performs following operations.
1) Accepts task from Main thread.
2) Creates worker thread
3) Finishes the task in worker thread
4) Reports result back to Main Thread
AsyncTask is a generic class, which accepts 3 types of parameters while it is creating
Params – The type of parameters we pass from main thread to asynctask while we are creating asynctask
Progress – The type of data we want asynctask to update as progress
Result – The type of result data passed after the task is completed from worker thread to main thread
Methods in AsyncTask:
1) onPreExecute() – Which is called immediately when the AsyncTask is called, used to perform the operations when the task is created. Runs on Main thread
2) doInBackground(Params) – Called in the background thread after the onPreExecute is called. All the task related code is written here only. This method must be overriden in asynctask
3) onProgressUpdate(Progress) – This will be called when there is a need to update progress on Main thread. This would be called if we call publishProgress() method. It runs on Main thread
4) onPostExecute(Result) – This is the final method to execute. In this method, asynctask delivers result to main thread. Runs on Main Thread
Create AsyncTask:
1) Create a subclass of AsyncTask<Params, Progress, Result>
2) Override doInBackground method – mandatory
3) Override other required methods – optional
Start AsyncTask:
1) Create object of the subclass of AsyncTask
2) Create array of parameters – optional
3) Call execute(params) method – If we have parameters
(or)
Call execute() method – If we don’t have parameters