Using AsyncTask Android

Author: | Posted in Android, Quick Tips No comments

In this tutorial we will learn what is AsyncTask and using AsyncTask Android.

In android if we need to perform some background task like a network operation(calling webservice) or to perform time consuming complex data calculation like loading a large amount of data from database or to read/write large no of files in android.
We need to do it in a separate thread from main activity thread or main UI thread, Because it may possible that it will affect performance or may freeze UI of Application.

We can do it using a synchronized Thread but there are some android ways also one is using AsyncTask. AsyncTask gives us freedom to perform background tasks or operations and use their results in main activity UI thread with a synchronized order execution (one by one), using inbuilt methods of this class. Only subclass of AsyncTask will be used with a must overridden method  (doInBackground(Params...)) and other can override as per our requirement like (onPostExecute(Result)) or (onPreExecute()).

Let’s have a look on AsyncTask class methods

    class LoadBackgroudData extends AsyncTask<URL, Integer, String> {
        protected void onPreExecute() {
            // TODO Auto-generated method stub
        protected String doInBackground(URL... params) {
            // TODO Auto-generated method stub
            return null;
        protected void onProgressUpdate(Integer... values) {
            // TODO Auto-generated method stub
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub

Understanding parameters in AsyncTask :

    class LoadBackgroudData extends AsyncTask<Params, Progress, Result>

1. Params, type of the parameters sent to the task while execution basically we use String or URL.

2. Progress, type of progress during background calculation(Integer, Double).

3. Result, type of result after task execution.

If you don’t want to use a type or all simply use Void type.

    class LoadBackgroudData extends AsyncTask<Void, Void, Void>

To execute a AsyncTask use

// example
    new LoadBackgroudData().execute(Params);
// send multiple arguments
    new LoadBackgroudData().execute(url, url, url...);
// without any argument
    new LoadBackgroudData().execute();
AsyncTask Andorid | Android Quick Tips

AsyncTask Andorid | Android Quick Tips


Understanding methods in AsyncTask :

When a AsyncTask is executed these four methods are called.

1. onPreExecute(), this is the first method in queue while executing AsyncTask. This step is basically used to start showing a ProgressBar/ProgressDialog on main UI.

2. doInBackground(Params...), after complition of onPreExecute(), doInBackground() started. This method is used to perform background computational processes. The parameters(Params) of the asynchronous task are passed to this step as argument. The result of the computation is returned by this step and will be passed back to onPostExecute(). This method can use publishProgress(Progress...) to publish progress on the main UI thread, in the onProgressUpdate(Progress...) step.

3. onProgressUpdate(Progress...), invoked after a call to publishProgress(Progress...) in doInBackground(). The timing of the execution is undefined. This method is used to display progress in the main UI while the background computation is executing. For example, it can be used to animate a progress bar or display logs.

4. onPostExecute(Result), this method calles after the background computation finishes. The result of the doInBackground() is passed to this method as a parameter. Used to show result on main UI or hide ProgressBar/ProgressDialog.

How to cancel AsyncTask :

We can cancel any time a AsyncTask by calling cancel(boolean). and we can check cancel state of AsyncTask using isCancelled() with returning boolean value.

Rules while using AsyncTask :

The AsyncTask class must be loaded on the main UI thread and the task instance must be created on the main UI thread. Also the execute(Params...) must be called on the UI thread. Do not call AsyncTask subclass methods manually. The task can be executed only once after initiating an exception will be thrown if a second execution is attempted.)

(Visited 506 times, 1 visits today)