How to use AsyncTask in Android App

Today we will be learning about how to use AsyncTask in Android Application. Every Android app use Thread to do some background work. But when it come to Threads there is always some confusion in developers head about handling Threads. Android made this simple by providing AsyncTask which handle the dirty work so that you can concentrate on your Business logic.

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally 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 ExecutorThreadPoolExecutor and FutureTask .

When an asynchronous task is executed, the task goes through 4 steps:

  1. onPreExecute() , invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
  2. doInBackground(Params…) , invoked on the background thread immediately after onPreExecute() 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 use  publishProgress(Progress…) to publish one or more units of progress. These values are published on the UI thread, in the  onProgressUpdate(Progress…) step.
  3. onProgressUpdate(Progress…) , invoked on the UI thread after a call to publishProgress(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.
  4. 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.

In this tutorial we have created a AsyncTaskRunner class by extending the AsyncTask class. Our class just sleep as if now for the specified time in EditText which will be provided by the user. It is repeating the sleeping process 10 times so that we can publish update for each sleep cycle on UI thread using publishProgress function.

Note : This tutorial is based on Android Studio 2.2, Java 1.7 and Android 6.0.

AsyncTask Implementation

1 Implementation of MainActivity.java class

1.1  First we Override onPreExecute function which is called first. This function is basically used to do setup for the processing like showing loader etc.

	@Override
	protected void onPreExecute() {
		// Things to be done before execution of long running operation. For
		// example showing ProgessDialog
	}

1.2 Next we Override doInBackground function which will run on separate Thread . The time taking work is done in this function . We can call publishProgress function on this to publish any updates on UI thread. On calling this function here it calls onProgressUpdate on UI thread along with supplied result. This function return result which is provided in function onPostExecute.

@Override
protected String doInBackground(String... params) {
    publishProgress("Sleeping..."); // published update to
    // onProgressUpdate function
    try {
        int time = Integer.parseInt(params[0]);
        // Sleeping for given time period for 10 times
        for (int i = 0; i < 10; i++) {
            Thread.sleep(time);
            publishProgress("Sleeping..." + (i + 1) + "*" + time
                    + " ms");
        }

        resp = "Slept for " + time + "*10 milliseconds";
    } catch (InterruptedException e) {
        e.printStackTrace();
        resp = e.getMessage();
    } catch (Exception e) {
        e.printStackTrace();
        resp = e.getMessage();
    }
    // return result to onPostExecute function
    return resp;

1.3 Next is onProgressUpdate function which is called when publishProgress function is called in previous function. This is mainly used to update progress on UI thread.

protected void onProgressUpdate(String... text) {
    finalResult.setText(text[0]);
    // Things to be done while execution of long running operation is in
    // progress. For example updating ProgessDialog
}

1.3 Finally onPostExecute is called when work is completed . This function is used for cleanup like removing loader  and publish final result which was passed.

protected void onPostExecute(String result) {
    // result published on completion of doInBackground function
    finalResult.setText(result);
}

Final implementation of MainActivity.java 

package com.androidsrc.asynctaskexample;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
    private Button button;
    private EditText time;
    private TextView finalResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        time = (EditText) findViewById(R.id.et_time);
        button = (Button) findViewById(R.id.btn_do_it);
        finalResult = (TextView) findViewById(R.id.tv_result);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // created instance of AsyncTaskRunner class which extends
                // AsyncTask
                AsyncTaskRunner runner = new AsyncTaskRunner();
                String sleepTime = time.getText().toString();
                runner.execute(sleepTime); // time from editText
            }
        });
    }

    private class AsyncTaskRunner extends
            AsyncTask<String, String, String> {

        private String resp;

        // this function run on seperate thread to do background work
        // do your time taking work here
        @Override
        protected String doInBackground(String... params) {
            publishProgress("Sleeping..."); // published update to
            // onProgressUpdate function
            try {
                int time = Integer.parseInt(params[0]);
                // Sleeping for given time period for 10 times
                for (int i = 0; i < 10; i++) {
                    Thread.sleep(time);
                    publishProgress("Sleeping..." + (i + 1) + "*" + time
                            + " ms");
                }

                resp = "Slept for " + time + "*10 milliseconds";
            } catch (InterruptedException e) {
                e.printStackTrace();
                resp = e.getMessage();
            } catch (Exception e) {
                e.printStackTrace();
                resp = e.getMessage();
            }
            // return result to onPostExecute function
            return resp;
        }

        @Override
        protected void onPostExecute(String result) {
            // result published on completion of doInBackground function
            finalResult.setText(result);
        }

        @Override
        protected void onPreExecute() {
            // Things to be done before execution of long running operation. For
            // example showing ProgessDialog
        }

        @Override
        protected void onProgressUpdate(String... text) {
            finalResult.setText(text[0]);
            // Things to be done while execution of long running operation is in
            // progress. For example updating ProgessDialog
        }
    }
}

2 Other components

2.1 This is implementation of main_activity.xml

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/tv_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="16dp"
        android:text="Sleep time in milliseconds:"
        android:textColor="#444444"
        android:textSize="15dp" />

    <EditText
        android:id="@+id/et_time"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tv_time"
        android:layout_marginTop="5dp"
        android:inputType="text" >
        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/btn_do_it"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/et_time"
        android:text="Run Async task" />

    <TextView
        android:id="@+id/tv_result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn_do_it"
        android:layout_marginLeft="9dip"
        android:layout_marginTop="15dip"
        android:text=""
        android:textColor="#AA0000"
        android:textSize="15dp" />

</RelativeLayout>

Testing the application

Now compile app on eclipse and then press run. You have to input time for sleep and then press “Run Async task”

Any further queries or custom tutorial please comment or mail us at androidsrcdotnet@gmail.com

GuRu

Technology enthusiast. Loves to tinker with things. Always trying to create something wonderful using technology. Loves coding for Android, Raspberry pi, Arduino , Opencv and much more.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *