Following is a quick code snippet of how to use runOnUiThread() method :

this@MainActivity.runOnUiThread(java.lang.Runnable {
    progressBar.visibility = View.GONE
})

Android runOnUiThread Example

Android runOnUiThread Example – In this Android Tutorial, we shall learn how to use runOnUiThread with an Example Android Application.

runOnUiThread runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.

ADVERTISEMENT

If you try to touch view of UI thread from another thread, you will get Android CalledFromWrongThreadException.

Following is an example Android Application demonstrating the usage of runOnUiThread() method.

Android runOnUiThread Example

Create Android Application with Kotlin Support with following details and rest values to default.

Application NamerunOnUiThread Example
Company nametutorialkart.com
Minimum SDKAPI 21: Android 5.0 (Lollipop)
ActivityEmpty Activity

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    tools:context="com.tutorialkart.runonuithreadexample.MainActivity">

    <TextView
        android:id="@+id/textview_msg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

</LinearLayout>

MainActivity.kt

package com.tutorialkart.runonuithreadexample

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

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

        // start some dummy thread that is different from UI thread
        Thread(Runnable {
            // performing some dummy time taking operation
            var i=0;
            while(i<Int.MAX_VALUE){
                i++
            }

            // try to touch View of UI thread
            this@MainActivity.runOnUiThread(java.lang.Runnable {
                this.textview_msg.text = "Updated from other Thread"
            })
        }).start()
    }
}