AsyncTask: The Deprecated Way to Do Background Work
AsyncTask was Android's original tool for short background tasks that update the UI. It was used for simple network requests or disk I/O. It's fully deprecated due to memory leaks and lifecycle issues; use Kotlin Coroutines instead.
WHY IT EXISTS Android's main UI thread cannot be blocked. Any long-running operation like a network call or database query will freeze the app, leading to an "Application Not Responding" (ANR) error. AsyncTask was created as a simple helper class to perform these operations on a background thread and publish the results back on the UI thread without manual thread management.
THE MENTAL MODEL Think of AsyncTask as a temporary worker you hire for a single job. You give them instructions on what to do in the background (doInBackground), they go away and work, and then they report the result back to you on the main thread (onPostExecute) so you can safely update the UI. You don't have to manage the communication details yourself.
HOW IT WORKS AsyncTask uses generics to define types for its parameters, progress updates, and final result. It orchestrates work across four main steps: first, onPreExecute runs on the UI thread for setup; second, doInBackground runs on a background thread to perform the heavy lifting; third, onProgressUpdate can be called from the background to publish progress to the UI thread; and fourth, onPostExecute delivers the final result to the UI thread.
WHEN TO USE IT You should not use AsyncTask in new code. Its only modern relevance is in maintaining very old Android applications that were written before its deprecation and have not yet been migrated to modern concurrency patterns like Kotlin Coroutines.
WHEN NOT TO USE IT Do not use AsyncTask in any new development, as it was deprecated in Android 11 (API 30). It is infamous for causing memory leaks because it holds a reference to the hosting Activity or Fragment. If the screen is rotated, the old Activity is destroyed but AsyncTask keeps it in memory. It's a poor choice for long-running tasks. Use Kotlin Coroutines with ViewModel and LiveData/Flow instead.
ONE CANONICAL EXAMPLE A classic use case was downloading an image from a URL. The doInBackground method would take the URL string, open an HTTP connection, and decode the image into a Bitmap. The onPostExecute method would then receive this Bitmap on the main thread and set it on an ImageView. This entire pattern is now better and more efficiently handled by image-loading libraries like Glide or Coil.
Read the original → developer.android.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.