Android AsyncTask: You can interact with the UI thread (Main Thread) with AsynTask when you have to do some background task. AsyncTask class performs background operations and publishes results on the UI thread without having to manipulate threads.
In your application, you can use the android AsyncTask class for short operations or tasks ( few seconds), for the long-running operation you have to choose another option.
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,Params
Progress
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.
private class MyTask extends AsyncTask<Void, Void, 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 afteronPreExecute()
finishes executing.onProgressUpdate(Progress...)
, invoked on the UI thread after a call topublishProgress(Progress...)
.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
- The first rule AsyncTask class must be loaded on the UI thread, it will be done automatically.
execute(Params...)
must be invoked on the UI thread.- Do not call
onPreExecute()
,onPostExecute(Result)
,doInBackground(Params...)
,onProgressUpdate(Progress...)
manually. - 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 format 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
<manifest> <uses-permission android:name="android.permission.INTERNET"/> .... </manifest>
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
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.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="in.eyehunt.androidasynctaskkotlin.MainActivity"> <TextView android:id="@+id/tv_result" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginEnd="8dp" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:text="Data will show !" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.029" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <ProgressBar android:id="@+id/progressBar" style="?android:attr/progressBarStyleHorizontal" android:layout_width="213dp" android:layout_height="26dp" android:layout_marginEnd="8dp" android:layout_marginStart="8dp" android:layout_marginTop="220dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.503" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" android:visibility="gone" android:indeterminate="true"/> </android.support.constraint.ConstraintLayout>
Step 4. Create an inner class in MainActivity kotlin class and extend AsyncTask class
package `in`.eyehunt.androidasynctaskkotlin import android.app.AlertDialog import android.app.Dialog import android.app.ProgressDialog import android.opengl.Visibility import android.os.AsyncTask import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.View import android.widget.ProgressBar import kotlinx.android.synthetic.main.activity_main.* import java.io.BufferedReader import java.io.InputStream import java.io.InputStreamReader import java.net.HttpURLConnection import java.net.URL class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val url = URL("https://api.github.com/search/users?q=eyehunt") MyAsyncTask().execute(url) } // AsyncTask inner class inner class MyAsyncTask : AsyncTask<URL, Int, String>() { private var result: String = ""; override fun onPreExecute() { super.onPreExecute() progressBar.visibility = View.VISIBLE } override fun doInBackground(vararg params: URL?): String { val connect = params[0]?.openConnection() as HttpURLConnection connect.readTimeout = 8000 connect.connectTimeout = 8000 connect.requestMethod = "GET" connect.connect(); val responseCode: Int = connect.responseCode; if (responseCode == 200) { result = streamToString(connect.inputStream) } return result } override fun onProgressUpdate(vararg values: Int?) { super.onProgressUpdate(*values) } override fun onPostExecute(result: String?) { super.onPostExecute(result) progressBar.visibility = View.GONE //set result in textView tv_result.text = result } } fun streamToString(inputStream: InputStream): String { val bufferReader = BufferedReader(InputStreamReader(inputStream)) var line: String var result = "" try { do { line = bufferReader.readLine() if (line != null) { result += line } } while (line != null) inputStream.close() } catch (ex: Exception) { } return result } }
Step 4. Run the application, in the emulator or on your android device
Output screenshot Android AsyncTask example in kotlin
Download Android AsyncTask example source code :
https://github.com/EyeHunts/AndroidAsyncTaskKotlin/
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)
MinSdkVersion=”15″
TargetSdkVersion=”26″
Coding in Kotlin