Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 104 ยท Coroutines and Background Work

Threads, Handlers, Looper and Volley (Legacy)

Understand the Android main thread, Thread and Executor, Handler, Looper and HandlerThread, runOnUiThread, AsyncTask's removal and Volley, and why coroutines replaced them.

Open an older Android project, or read an older answer online, and you will meet a vocabulary that does not appear in modern tutorials: Handler, Looper, HandlerThread, runOnUiThread, AsyncTask, Volley. They are the tools Android developers used for more than a decade to run work off the main thread and put the result back on it. You do not need them for new code, because coroutines do the same job with far less ceremony. You do need to read them, because real codebases, libraries and interviews still use them, and because they explain why the main thread behaves the way it does.

This lesson explains the main thread and its message queue, the legacy tools in the order they were invented, what Volley is and how its request queue and cache work, and how each one maps to a coroutine. The Android classes cannot run here, so the real code is read-only. The TryIts are plain Kotlin stand-ins that run real JVM threads to model a looper, a handler and a request queue, and the text says which part is the stand-in.

The main thread and its message queue

Every Android app has one special thread, the main thread (also called the UI thread). It draws the screen, handles taps and runs lifecycle callbacks such as onCreate. It works through a message queue: a list of things to do (a tap, a frame to draw, a callback), taken one at a time by a loop. The loop is called a Looper, and the objects that post work into the queue are Handlers.

flowchart LR
    T1["Tap event"] --> Q["MessageQueue"]
    T2["Frame draw"] --> Q
    T3["Handler.post(...)"] --> Q
    Q --> L["Looper<br/>runs one item at a time"]
    L --> C["Your code<br/>on the main thread"]

One thread, one queue. While your code runs, nothing else in the queue can.

Two rules follow from that picture, and they are the reason all the tools below exist:

  1. Never block the main thread. If one item takes too long, the queue stalls: touches are ignored, animations freeze, and after about 5 seconds without responding to input, Android shows the ANR ("Application Not Responding") dialog. Network, disk and heavy computation belong elsewhere. Since API 11, a network call on the main thread throws NetworkOnMainThreadException, and StrictMode can flag disk access.
  2. Only touch views from the main thread. Views are not thread-safe. Updating a TextView from another thread throws CalledFromWrongThreadException ("Only the original thread that created a view hierarchy can touch its views").

So you always need two moves: get off the main thread for slow work, and get back on it to show the result.

The first stand-in builds a miniature looper on a real JVM thread, to make the queue idea concrete: a thread that takes tasks from a queue one at a time, with a delay option like postDelayed.

Kotlin A tiny Looper and Handler (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The two post calls without delay run first, in the order they were sent, and the delayed one runs after. That ordering is what the real MessageQueue gives you, and it is why code posted to the main thread never runs in the middle of other main-thread code: it waits its turn.

Thread and Executor

The most direct way off the main thread is a plain Thread:

Kotlin
// read-only example: a raw thread and the way back
Thread {
    val json = api.download()                   // slow: not allowed on the main thread
    runOnUiThread {                             // Activity method: post to the main thread
        textView.text = json.title
    }
}.start()

This works, but each Thread is expensive to create and nothing limits how many you start. A tap on a button that starts a new thread every time can create hundreds. An ExecutorService fixes that with a pool of reusable threads and a queue of tasks:

Kotlin
// read-only example: a fixed pool shared by the app
object AppExecutors {
    val io: ExecutorService = Executors.newFixedThreadPool(4)
}

AppExecutors.io.execute {
    val items = repository.loadItemsBlocking()
    view.post { adapter.submit(items) }         // View.post: run this on the UI thread
}

Getting back to the main thread

There are three common ways, all of which post a Runnable into the main looper's queue:

  • Activity.runOnUiThread(Runnable) runs it at once if you are already on the main thread, otherwise posts it.
  • View.post(Runnable) posts it to the view's thread, after the view is attached. A well-known use was "run this after the view has been measured".
  • Handler(Looper.getMainLooper()).post { ... } is the general form and works from any class that has no Activity or View.
Kotlin
// read-only example: the three ways back
activity.runOnUiThread { title.text = "Done" }
title.post { title.text = "Done" }
Handler(Looper.getMainLooper()).post { title.text = "Done" }

All three assume that the Activity or View is still alive. If the user rotated the screen while your thread worked, you update a dead Activity or leak it, because the thread holds a reference. This is the leading bug of the legacy approach: nothing cancels the work for you.

Handler, Looper and HandlerThread

The Handler is the more flexible tool. A Handler is bound to one Looper (one thread and its queue). Whatever you post through that handler runs on that looper's thread. Besides post, it supports postDelayed (run after a delay) and sendMessage with a Message object carrying an integer code and payload, handled in handleMessage.

Kotlin
// read-only example: a handler with messages and delays
private val handler = Handler(Looper.getMainLooper())

private val blink = object : Runnable {
    override fun run() {
        cursor.visibility = if (cursor.isVisible) View.INVISIBLE else View.VISIBLE
        handler.postDelayed(this, 500)          // schedule the next blink
    }
}

override fun onStart() { super.onStart(); handler.post(blink) }
override fun onStop() { handler.removeCallbacks(blink); super.onStop() }   // forgetting this leaks

Worker threads are ordinary threads with no looper, so a Handler created on one throws Can't create handler inside thread that has not called Looper.prepare(). A HandlerThread is a thread that has a looper, so you can post tasks to it and they run one at a time, in order on that background thread. It is the classic tool for a serial background queue, such as a single writer to a file.

Kotlin
// read-only example: a serial background thread
val worker = HandlerThread("db-writer").apply { start() }
val workerHandler = Handler(worker.looper)

workerHandler.post { file.appendText("first\n") }
workerHandler.post { file.appendText("second\n") }    // always after "first"

// when done
worker.quitSafely()

The next stand-in models exactly this: a UI looper, a background looper (a HandlerThread), and the hop between them. A background task posts its result to the UI looper, which is the way back. Thread names in the output show where each step runs.

Kotlin HandlerThread and the hop back to the UI (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You can see the three properties that matter: the click handler returns at once, the records are saved in order on the worker (serial queue), and the final message is delivered on the UI thread, where touching views is legal.

Thread priority

Every thread has a priority that tells the scheduler how much CPU it deserves compared with the others. On Android there are two related scales:

  • Thread.setPriority(1..10), the Java scale (Thread.MIN_PRIORITY, NORM_PRIORITY = 5, MAX_PRIORITY). It is only a hint.
  • android.os.Process.setThreadPriority(...), the Linux nice value that the Android scheduler actually uses. Lower numbers mean higher priority: THREAD_PRIORITY_DEFAULT is 0, THREAD_PRIORITY_BACKGROUND is 10, THREAD_PRIORITY_URGENT_DISPLAY is -8 (used for the UI thread) and THREAD_PRIORITY_LOWEST is 19.
Kotlin
// read-only example: background work should not steal time from the UI thread
val worker = Thread {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND)   // call from inside the thread
    syncOfflineData()
}
worker.start()

Threads created with Thread inherit the priority of the thread that created them, so a worker started from the main thread would run at UI priority unless you lower it. HandlerThread takes a priority in its constructor (HandlerThread("io", Process.THREAD_PRIORITY_BACKGROUND)), and coroutine dispatchers and WorkManager pick sensible defaults for you. Priority never replaces correct design: a low-priority thread can still hold a lock the main thread needs, so keep shared state small and avoid blocking the main thread at all.

AsyncTask and why it was removed

AsyncTask was introduced in Android 1.5 to hide the thread-and-handler dance. You overrode doInBackground (runs on a worker), and onPostExecute (runs on the main thread with the result), and the class did the hop for you.

Kotlin
// read-only example: legacy AsyncTask (deprecated in API 30, removed from new SDKs)
class LoadTask(private val activity: MainActivity) : AsyncTask<String, Void, List<Item>>() {
    override fun doInBackground(vararg urls: String): List<Item> = download(urls[0])
    override fun onPostExecute(result: List<Item>) { activity.show(result) }   // leak and crash risk
}
LoadTask(this).execute("https://example.com/items")

It looked simple and caused many bugs: the inner class held a reference to the Activity (a memory leak), results arrived after the Activity was gone (crashes), configuration changes restarted the work, exceptions were hard to handle, and the default executor changed from parallel to serial between versions. Google deprecated AsyncTask in API 30 (Android 11) and it is slated for removal; do not use it. If you find it in a project, replace it with a coroutine in a ViewModel (see the mapping below), or with WorkManager if the work must survive the app.

Volley: a request queue for HTTP

Volley is an HTTP library released by Google in 2013, built on this model of threads and queues. You build a Request (a string, JSON or image request), add it to a RequestQueue, and Volley runs it on its own network threads and delivers the result on the main thread through callbacks, so you can update views directly. It also provides request prioritization, retries with backoff, cancellation by tag and an automatic disk and memory cache that respects HTTP caching headers.

Kotlin
// read-only example: Volley (com.android.volley:volley)
val queue = Volley.newRequestQueue(context)           // one queue for the whole app

val request = JsonObjectRequest(
    Request.Method.GET, "https://api.example.com/items/1", null,
    { response -> titleView.text = response.getString("title") },       // main thread
    { error -> Toast.makeText(context, "Failed: ${error.message}", Toast.LENGTH_SHORT).show() },
).apply {
    tag = "item-screen"
    setRetryPolicy(DefaultRetryPolicy(2_500, 2, 1f))  // timeout ms, retries, backoff multiplier
}
queue.add(request)

// when the screen goes away
queue.cancelAll("item-screen")

For a JSON array at the top level ([ {...}, {...} ]), use JsonArrayRequest the same way; its success callback receives a JSONArray that you loop with for (i in 0 until array.length()) array.getJSONObject(i). StringRequest gives you the raw body, and for POST requests you override getParams() (form fields) or send a JSONObject body with JsonObjectRequest(Request.Method.POST, url, body, ...). Parse into data classes with a JSON library when the shape gets complicated (JSON in Android).

Under the hood, a Volley RequestQueue runs one cache dispatcher thread and a few network dispatcher threads (four by default). A new request goes first to the cache thread: a fresh cached response is delivered immediately, an expired or missing one is handed to a network thread, and the result is stored back in the cache. The delivery to the callbacks happens on the main thread.

flowchart LR
    A["queue.add(request)"] --> C{"Cache<br/>dispatcher"}
    C -->|"fresh hit"| D["Deliver on main thread"]
    C -->|"miss or expired"| N["Network dispatcher<br/>(4 threads)"]
    N --> W["Write to cache"] --> D

Volley checks the cache first on one thread, then goes to the network on a pool.

Volley is still maintained and works, and you will find it in older apps for small JSON calls and image loading (NetworkImageView). It has no coroutine support, parses nothing for you (you convert JSON by hand), and is poor at large downloads, because its responses are held in memory. For new code, Retrofit with OkHttp and JSON serialization replace it, and Coil replaces its image loader.

The third stand-in models Volley's queue: a cache check first, network workers for misses, retries and cancellation by tag.

Kotlin A Volley-style request queue with cache (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The modern replacement: coroutines

Every concept above has a cleaner equivalent in coroutines:

Legacy tool What it did Modern replacement
Thread { ... }.start() Run off the main thread viewModelScope.launch(Dispatchers.IO) { ... }
ExecutorService pool Limit threads, reuse them Dispatchers.IO / Dispatchers.Default (shared pools)
runOnUiThread, View.post, Handler(mainLooper).post Return to the main thread withContext(Dispatchers.Main), or collect a StateFlow
Handler.postDelayed Do something later delay(500) inside a coroutine
HandlerThread Serial background queue Mutex, a single-thread dispatcher, or a Channel consumed by one coroutine
AsyncTask Background work plus a callback on the main thread A suspend function called from viewModelScope
Volley RequestQueue Queued HTTP with cache Retrofit/OkHttp with suspend functions
queue.cancelAll(tag) Cancel work when the screen leaves Cancelling the scope (automatic for viewModelScope)

The big gain is structured concurrency: work belongs to a scope, and cancelling the scope cancels all of it, which fixes the leak that haunted the older tools. Here is the same "download and show" flow written both ways.

Kotlin
// read-only example: legacy
Thread {
    val items = api.loadItemsBlocking()
    runOnUiThread { adapter.submit(items) }
}.start()                                       // nothing cancels it if the screen is gone

// read-only example: modern (in a ViewModel)
fun load() {
    viewModelScope.launch {                      // cancelled when the ViewModel is cleared
        val items = withContext(Dispatchers.IO) { repository.loadItems() }
        _state.value = UiState.Loaded(items)     // back on the main thread automatically
    }
}

When you meet legacy code, do not rewrite it blindly. First find out what it does and what thread each part runs on. Then replace one piece at a time, starting with whatever leaks the Activity. A Handler used for a blinking cursor or a debounce is fine to leave if it is removed in onStop.

Common mistakes

  • Blocking the main thread with network, disk or a long loop. Result: jank and ANR.
  • Touching a view from a worker thread. Post back to the main thread first.
  • Starting a raw Thread per event. Use a pool, or better, coroutines.
  • Not removing handler callbacks. A postDelayed that outlives the screen leaks the Activity and may crash when it fires.
  • Creating a Handler() on a thread without a looper. Use Looper.getMainLooper() or a HandlerThread.
  • Using AsyncTask in new code. It is deprecated and unsafe on configuration changes.
  • Forgetting to cancel a Volley request. Give requests a tag and call cancelAll when the screen goes away.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main thread's Looper?

    The Looper drains the MessageQueue in order. While one item runs, nothing else in the queue can, which is why blocking it freezes the UI.
  2. 2. A background thread calls textView.setText(...). What happens?

    Views may only be touched from the thread that created them, normally the main thread. Post back to it first.
  3. 3. Which tool gives you a background thread that runs posted tasks one at a time in order?

    A HandlerThread has its own Looper, so tasks posted through its Handler run serially on that background thread.
  4. 4. Why was AsyncTask deprecated?

    Its design tied background work to a UI component without cancellation. Coroutines in a ViewModel scope replace it.
  5. 5. What does Volley do when you add a request whose response is already fresh in its cache?

    The cache dispatcher checks the cache first. Only a miss or an expired entry goes to the network threads.

Summary

  • The main thread runs a Looper over a message queue; blocking it freezes the UI and causes ANRs, and only it may touch views.
  • Legacy code moves work off the main thread with Thread or ExecutorService and returns with runOnUiThread, View.post or Handler(Looper.getMainLooper()).
  • A Handler posts to one Looper; postDelayed schedules later work and must be cancelled in onStop; a HandlerThread is a serial background queue.
  • AsyncTask is deprecated (API 30) because of leaks and lifecycle bugs; do not use it in new code.
  • Volley runs a RequestQueue with a cache thread and network threads, delivers callbacks on the main thread and supports retries and cancel by tag.
  • Coroutines replace all of this with structured concurrency: scopes cancel their work, and withContext switches threads.
  • The Android code is read-only; the TryIts model a looper, a HandlerThread hop and a Volley-like queue on JVM threads.

Next: Services, Notifications and Foreground Work