Hello
Friends,
Today
I’ll discuss about “AsyncTask”. It stands for
Asynchronous Task, which is one of the most important concept used in
android development. It’s more or less related to thread concept
used in various languages.
Definition
: An asynchronous task is defined by a computation that runs
on a background thread and whose result is published on the UI
thread.
Let’s
understand this in this way, whenever we download anything using our
browser, the downloading process is done by the browser in the
background while we still surf the other web pages. It means, the
downloading process doesn’t affect the working of browser. In this
example we can relate the term UI with browser and downloading
process with AsyncTask(background thread). It
is highly recommended that we should not use AsyncTask for long
operations.AsyncTask
is an abstract class which is defined by 3 generic types, called
Params,
Progress
and Result. I
personally recommend you to brush-up the concepts of Generic Types,
Abstract Class and preferably File Handling before getting into this.
In
order to use AsyncTask class,
we
must subclass it.
private
class DownloadingTask extends AsyncTask<URL, Integer, Long> This AsyncTask class provides us the followingmethods to override and we must override at least one.1.OnPreExecute()2.doInBackground(Params...)[most often we override this method]3.onProgressUpdate(Progress...)4.onPostExecute(Result)
Note :Do not callany of the above mentioned methodsmanually.
When
an asynchronous task is executed, the task goes through 4 steps:-
onPreExecute(), As the method name suggests, it is invoked on the UI thread before the task is executed. In simple term we can understand this like, arranging all the required documents before going for an interview. -
doInBackground(Params...), This method is invoked on the background thread immediately afteronPreExecute()finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also usepublishProgress(Progress...)to publish one or more units of progress. These values are published on the UI thread, in theonProgressUpdate(Progress...)step. -
onProgressUpdate(Progress...), invoked on the UI thread after a call topublishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field. -
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.source: