In this tutorial, we’ll learn and implement AsyncTask using Kotlin in our Android Application.

What is Android AsyncTask?

Android AsyncTask is an abstract class that’s used to perform long operations in the background. We have to extend this class and implement the abstract methods to use async tasks in our app.

The three type parameters of an asynchronous task are:

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

AsyncTask Methods

AsyncTask has four methods that are triggered at different times during the life cycle of async task execution.

  1. PreExecute: This is invoked in UI thread before the AsyncTask is executed. We can show a ProgressBar or perform any UI related tasks in this method.
  2. doInBackground: The background execution code goes in this method. We cannot call the Activity’s UI instances in this method.
  3. onProgressUpdate: This method gets triggered when the publish progress is invoked in the doInBackground method. This method comes handy if you wish to inform UI thread about the current progress.
  4. onPostExecute: gets triggered after doInBackground is over. The values returned from the doInBackground are received here. We can do the UI changes here such as updating the views with the values returned.

How to Create AsyncTask in Kotlin?

The execute method starts the AsyncTask. We can pass anything in the constructor, generally a context is passed.

AsyncTasks are defined as inner classes. We have to define them as static to prevent memory leaks.

In Kotlin, companion object is the equivalent of static classes. So AsyncTasks are defined in a companion object.

Why non-static AsyncTask can cause memory leaks?

When non-static, they hold a reference to the Activity. So, if the AsyncTask exists till after the Activity’s lifecycle, it’ll keep a reference of the Activity thereby causing memory leaks.

Hence companion object is used where we can store a weak reference of the Activity.

Android AsyncTask Kotlin Project Structure


1. XML Layout Code

The code for the activity_main.xml layout file is given below:

2. Kotlin Activity Class Code

The MainActivity.kt Kotlin Activity class is given below.

When we click the button, AsyncTask is launched in the background.

We pass an Int value in the AsyncTask that represents the number of seconds.

In the doInBackground method, we are putting the thread to sleep for the given number of seconds.

We are triggering the progressUpdate with a String that gets displayed in the Toast.

In the onPostExecute method, we are hiding the ProgressBar and setting the TextView to the string returned by unwrapping the Kotlin Nullable Type.

3. AsyncTask App Output

The output of the above application in action is given below.

android asynctask app output

By admin

Leave a Reply

%d bloggers like this: