Skip to main content

How to update UI from a background thread using a Handler in Kotlin Android

How to update UI from a background thread using a Handler in Kotlin Android.

Here's a detailed step-by-step tutorial on how to update the UI from a background thread using a Handler in Kotlin for Android.

  1. Create a new Android project in Kotlin and open the main activity file.

  2. Declare a Handler object as a member variable in your activity class. This handler will be used to update the UI from the background thread.

private val handler = Handler(Looper.getMainLooper())
  1. In your background thread where you want to update the UI, create a Runnable object that contains the code to update the UI.
val runnable = Runnable {
// Code to update the UI
textView.text = "UI updated from background thread"
}
  1. Inside the background thread, use the Handler object to post the Runnable to the main thread's message queue.
handler.post(runnable)
  1. Now, when the background thread executes the post method, the Runnable will be added to the main thread's message queue. The code inside the Runnable will be executed on the main thread, allowing you to update the UI.

Here's an example of how you can use these steps in a real-world scenario:

class MainActivity : AppCompatActivity() {

private lateinit var textView: TextView
private val handler = Handler(Looper.getMainLooper())

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

textView = findViewById(R.id.textView)

// Start a background thread
Thread {
// Simulate some time-consuming task
Thread.sleep(2000)

// Create a Runnable object to update the UI
val runnable = Runnable {
// Update the UI
textView.text = "UI updated from background thread"
}

// Post the Runnable to the main thread's message queue
handler.post(runnable)
}.start()
}
}

In this example, the background thread simulates a time-consuming task by sleeping for 2 seconds. After the sleep, the Runnable is posted to the main thread's message queue using the Handler, and the UI is updated with the desired text.

That's it! You've successfully updated the UI from a background thread using a Handler in Kotlin for Android.