Threads: Your App's Second Pair of Hands

A thread is a separate path of execution for background work, keeping your app's UI responsive. It's used for long tasks like network calls or disk I/O. The main footgun is trying to update the UI from a background thread, which will crash your app.
WHY IT EXISTS Android apps have a single main thread, also known as the UI thread, which handles all user interface updates and interactions. If you perform a long-running operation like a network request on this thread, the UI freezes. The system will eventually show an 'Application Not Responding' (ANR) dialog. Threads allow you to offload these long operations to the background, keeping the UI smooth and responsive.
THE MENTAL MODEL Think of your app as a coffee shop. The main thread is the cashier who takes orders and interacts with customers. A background thread is the barista who makes the coffee. If the cashier tried to make a complex latte, the line of customers would grind to a halt. Instead, the cashier passes the order to the barista and can immediately serve the next customer. The app's UI (the cashier) remains available while the background work (the barista) is being done.
HOW IT WORKS At its core, you create a new Thread object and give it a piece of work to do, typically in the form of a Runnable. When you call the thread's start() method, the Android system scheduler allocates CPU time for it to run concurrently with the main thread. The key rule is that this background thread cannot directly touch the UI. To show the result, it must post a message back to the main thread's queue, which can then safely update the screen.
WHEN TO USE IT Use a background thread for any operation that could take more than a few milliseconds to complete. This includes making network calls to fetch data from an API, reading or writing large files from disk, querying a database, or performing intensive calculations like processing an image.
WHEN NOT TO USE IT While fundamental, creating and managing raw Thread objects is often discouraged in modern Android development. It's complex to handle thread lifecycle, communication, and pooling efficiently, which can lead to bugs and performance issues. Higher-level abstractions like Kotlin Coroutines or WorkManager are almost always a better choice as they manage this complexity for you.
ONE CANONICAL EXAMPLE An app needs to download a user's profile image from a URL. The main thread shows a placeholder and a loading spinner. It then starts a background thread to handle the network request and download the image bytes. While the download is in progress, the user can still scroll and interact with the rest of the app. Once the download is complete, the background thread signals the main thread, which then replaces the placeholder with the downloaded image.
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.