AsyncTask was Android's helper class for running background operations and updating the UI thread with results. It was deprecated in API 30 (Android 11).
class DownloadTask : AsyncTask<URL, Int, String>() {
override fun onPreExecute() {
// Runs on UI thread - show loading
progressBar.visibility = View.VISIBLE
}
override fun doInBackground(vararg urls: URL): String {
// Runs on background thread
var progress = 0
urls.forEach { url ->
downloadFile(url)
progress += 25
publishProgress(progress) // Update progress
}
return "Complete"
}
override fun onProgressUpdate(vararg values: Int) {
// Runs on UI thread
progressBar.progress = values[0]
}
override fun onPostExecute(result: String) {
// Runs on UI thread
progressBar.visibility = View.GONE
textView.text = result
}
}
// Usage
DownloadTask().execute(url1, url2, url3)
UI Thread: onPreExecute() ──────────────────────── onPostExecute()
↓ ↑
Background: doInBackground() ─ publishProgress() ───┼
↓ │
UI Thread: onProgressUpdate() ────┘
1. Memory Leaks
class MyActivity : Activity() {
inner class MyTask : AsyncTask<...>() {
// Holds implicit reference to Activity
// Activity can't be garbage collected during task
}
}
2. Context Loss on Configuration Change
// Activity rotates while task is running
// Task completes, tries to update destroyed Activity → Crash!
3. Difficult Cancellation
task.cancel(true)
// But doInBackground keeps running unless you check isCancelled()
4. No Lifecycle Awareness
// Doesn't know about Activity/Fragment lifecycle
// Can cause crashes if UI is gone
5. Serial Execution by Default (API 13+)
// Tasks run one at a time on single background thread
// Can cause unexpected delays
1. Kotlin Coroutines (Recommended)
lifecycleScope.launch {
progressBar.visibility = View.VISIBLE
val result = withContext(Dispatchers.IO) {
downloadFile(url)
}
progressBar.visibility = View.GONE
textView.text = result
}
2. RxJava
Observable.fromCallable { downloadFile(url) }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { result -> textView.text = result }
3. Executors + LiveData
// Execute on background, post to LiveData
AsyncTask was simple but had fundamental design flaws. Use Coroutines with lifecycleScope for lifecycle-aware, leak-free background work.
Mark this when you can explain the answer in your own words.
Help fellow developers prepare for interviews
Sharing helps the Android community grow 💚