Android AsyncTask

Android AsyncTask is an abstract class provided by Android which gives us the liberty to perform heavy tasks in the background and keep the UI thread light thus making the application more responsive.

An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

The Application Main Thread

When an Android application is first started, the runtime system creates a
single thread in which all application components will run by default. This
thread is generally referred to as the main thread.

Due to this single thread model tasks that take longer time to fetch the response can make the application non-responsive. To avoid this we use android AsyncTask to perform the heavy tasks in background on a dedicated thread and passing the results back to the UI thread. Hence use of AsyncTask in android application keeps the UI thread responsive at all times.

The 4 steps

The 4 basic methods used,when an asynchronous task is executed are defined below:

  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.

AsyncTask’s generic types

The three types used by an asynchronous task are the following:

  1. Params: The type of the parameters sent to the task upon execution.
  2. Progress: The type of the progress units published during the background computation.
  3. Result: The type of the result of the background computation.

Android AsyncTask Example Code

The xml layout is defined in the activity_main.xml and its given below:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/myTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Async Demo"
        android:textSize="25sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.334" />

    <Button
        android:id="@+id/buttonClick"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="buttonClick"
        android:text="@string/press_me"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/myTextView"
        app:layout_constraintVertical_bias="0.425" />

</androidx.constraintlayout.widget.ConstraintLayout>

The MainActivity.java is defined below:

package in.codingtimes.asyncdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView myTextView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myTextView = (TextView) findViewById(R.id.myTextView);

    }
    public void buttonClick(View view){
        int i =0;
        while(i<=20){
            try {
                Thread.sleep(1000);
                i++;
            }
            catch (Exception e) {

            }
        }
        myTextView.setText("Button Pressed");
    }
}

With the code changes complete, run the application on either a physical
device or an emulator.

Once the application is running, touch the Button, at
which point the application will appear to freeze. It will, for example, not be
possible to touch the button a second time and in some situations the
operating system will, as demonstrated in Figure , report the application
as being unresponsive:

Clearly, anything that is going to take time to complete within the
buttonClick() method needs to be performed within a separate thread.

That’s it!
You have successfully completed the post. Do Share : )

Peace Out!

Also Read – Android Broadcast Receiver


Check Out Deals on -> Amazon , Flipkart , Myntra , Adidas , Apple TV , Boat , Canva , Beardo , Coursera , Cleartrip , Fiverr , MamaEarth , SwiggyKFC


One comment

Leave a Reply

Your email address will not be published.