Android AsyncTask example with progress bar in kotlin

Android AsyncTask: You can interact with UI thread (Main Thread) with AsynTask when you have to do some background task. AsyncTask class perform background operations and publish results on the UI thread without having to manipulate threads.

In your application, you can use android AsyncTask class for short operations or task ( few seconds), for the long-running operation you have to choose another option.

Android AsyncTask example with progress bar in kotlin android studio

AysnTask performs an operation (or any task) in the background and publishes results in UI Thread. An asynchronous task is defined by 3 generic types, called,ParamsProgress and Result.

  • Params,  the parameters sent to the task upon execution.
  • Progress, the progress units published during the background computation.
  • Result, the result of the background computation.


if you don’t want to pass any value then pass parameters Void.


There are 4 methods in Async task: onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

  • onPreExecute(), invoked on the UI thread before the task is executed.
  • doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing.
  • onPostExecute(Result), invoked on the UI thread after the background computation finishes.


How to cancel AsyncTask

A task can be canceled at any time by invoking cancel(boolean) method. Invoking this method will cause subsequent calls to isCancelled() to return true. So you can check Task has canceled or not.


Rules of Using AsyncTask

  • First rule AsyncTask class must be loaded on the UI thread, it will be done automatically.
  • The task can be executed only once (an exception will be thrown if a second execution is attempted.)


How to Use – Let’s Build AsyncTask android example 

This example we are downloading data from GitHub API in string formate and showing in TextView.

Step 1. Create new project “Build Your First Android App in Kotlin
Step 2. add internet permissions in manifest.xml, for internet connection

Step 3. Add flowing code in resource file main_activity.xml
TextView -> will show result
ProgressBar will visible when downloading start and invisible after the task has completed

Step 4. Create an inner class in MainActivity kotlin class and extend AsyncTask class

Step 4. Run the application, in the emulator or on your android device
Output screenshot Android AsyncTask example in kotlin

Android AsyncTask example tutorial


Download Android AsyncTask example source code  :


Note : This example (Project) is developed in Android Studio 3.0.1 ,tested on Android 7.1.1 ( Android Nougat), compile SDK version API 26: Android 8.0 (Oreo)



Coding in Kotlin

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.