Understanding Android AsyncTask
AsyncTask is a mechanism for executing operations in a background thread without having to manually handle thread creation or execution.It is designed to be used for short operations (a few seconds at the most). If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent
package such as Executor
, ThreadPoolExecutor
and Service.
Creating MyAsyncTask :
private class MyAsyncTask< Params, Progress, Result> {……}
The three types used by an asynchronous task are the following:
Params
, the type of the parameters sent to the task upon execution.Progress
, the type of the progress units published during the background computation.Result
, the type of the result of the background computation.
4 Stages of AsyncTask :
PreExecute
- invoked in UI thread before the task is executed.this step normally used to to setup task an showing progress bar.doInBackground
- executed in the background thread to do things like network downloads.onProgressUpdate
- executed in the main thread whenpublishProgress
is called from doInBackground.onPostExecute
- executed in the main thread to do things like set image views.