Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
How to automatically start and stop an Async task in Kotlin?
This example demonstrates how to automatically start and stop an Async task in Kotlin.
Step 1 − Create a new project in Android Studio, go to File ? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
Example
Step 3 − Add the following code to src/MainActivity.kt
Example
import android.os.AsyncTask
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import java.lang.ref.WeakReference
class MainActivity : AppCompatActivity() {
var variable = 10
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
runTask()
}
private fun runTask() {
val myToast = MyToast(this)
myToast.execute(10)
}
companion object {
class MyToast internal constructor(context: MainActivity) : AsyncTask() {
private var response: String? = null
private val activityReference: WeakReference = WeakReference(context)
override fun onPreExecute() {
val activity = activityReference.get()
if (activity == null || activity.isFinishing) return
activity.progressBar.visibility = View.VISIBLE
}
override fun doInBackground(vararg params: Int?): String? {
publishProgress("Async Started..") // Calls onProgressUpdate()
response = try {
val time = params[0]?.times(1000)
time?.toLong()?.let { Thread.sleep(it / 2) }
publishProgress("Half Time") // Calls onProgressUpdate()
time?.toLong()?.let { Thread.sleep(it / 2) }
publishProgress("Async Stopped..") // Calls onProgressUpdate()
"Android was sleeping for " + params[0] + " seconds"
} catch (e: InterruptedException) {
e.printStackTrace()
e.message
} catch (e: Exception) {
e.printStackTrace()
e.message
}
return response
}
override fun onPostExecute(result: String?) {
val activity = activityReference.get()
if (activity == null || activity.isFinishing) return
activity.progressBar.visibility = View.GONE
activity.textView.text = result.let { it }
activity.variable = 100
}
override fun onProgressUpdate(vararg text: String?) {
val activity = activityReference.get()
if (activity == null || activity.isFinishing) return
Toast.makeText(activity, text.firstOrNull(), Toast.LENGTH_SHORT).show()
}
}
}
}
Step 4 − Add the following code to androidManifest.xml
Example
activity android:name=".MainActivity">
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon
from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen

