Running User Interface Thread in Android using Kotlin
Last Updated :
23 Apr, 2024
User Interface Thread or UI-Thread in Android is a Thread element responsible for updating the layout elements of the application implicitly or explicitly. This means, that to update an element or change its attributes in the application layout ie the front-end of the application, one can make use of the UI-Thread.
Realizing UI Thread:
For example, a thread action is started, and the developer wants to update the front-end element with respect to the thread elements, the runOnUIThread{...} function can be used.
Below is an example of an application where a UI thread is used.
Sample App in which the Text in the TextView is changed Every Second
Initially, the application will show a Welcome message and as soon as the start button is clicked, it will show 2 messages, "love gfg" and "not gfg" alternatively at each second.
Approach:
Step 1: Add the below code in activity_main.xml. Here, add a TextView and a button to our MainActivity layout.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv1"
android:layout_width="210sp"
android:layout_height="100sp"
android:layout_centerInParent="true"
android:gravity="center"
android:textSize="50sp"
android:text="Welcome"
/>
<Button
android:id="@+id/btnStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"
android:layout_below="@id/tv1"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
Step 2: Add the below code in MainActivity. Here OnClickListener is added with the button. So it is invoked whenever the user clicks the button. In the listener, an infinite loop is created in the main thread and using the UI thread the text is changed after every second.
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Assigning Layout elements
val tv = findViewById<TextView>(R.id.tv1)
val btn = findViewById<Button>(R.id.btnStart)
val msg1 = "love gfg" val msg2 = "not gfg"
// Button onClick action
btn.setOnClickListener
{
// Declaring Main Thread
Thread(Runnable {
while (true) {
// Updating Text View at current
// iteration
runOnUiThread{ tv.text = msg1 }
// Thread sleep for 1 sec
Thread.sleep(1000)
// Updating Text View at current
// iteration
runOnUiThread{ tv.text = msg2 }
// Thread sleep for 1 sec
Thread.sleep(1000)
}
}).start()
}
}
}
Note: The While loop must be declared only inside the Thread. If a Thread is declared inside a while loop, the program doesn't work and crashes.
Sample Timer App
From the basic concept of the above code, a timer app can be designed. Below is the code for the same:
Approach:
Step 1: Add the below code in MainActivity layout. Here a button, edittext, and textview are added. The button is used to start the timer, edittext is used to take the input from the user, and textview is used to display the time left.
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btnStart"
android:layout_width="100sp"
android:layout_height="50sp"
android:layout_centerInParent="true"
android:text="Start"
/>
<EditText
android:id="@+id/et1"
android:layout_width="100sp"
android:layout_height="100sp"
android:layout_centerHorizontal="true"
android:layout_above="@id/btnStart"
android:textSize="50sp"
android:inputType="number"
android:gravity="center"
android:background="@color/colorPrimary"
android:textColor="@color/colorAccent"
/>
<TextView
android:id="@+id/tv1"
android:layout_width="100sp"
android:layout_height="100sp"
android:layout_centerHorizontal="true"
android:layout_below="@id/btnStart"
android:gravity="center"
android:textSize="50sp"
android:background="@color/colorPrimaryDark"
android:textColor="@color/colorAccent"
/>
</RelativeLayout>
Step 2: Add the below code in MainActivity class. Here we add the onClickListener with the button. As the button is clicked, runOnUiThread function is used to display the time left.
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Assigning Layout elements
val et = findViewById<EditText>(R.id.et1)
val btn = findViewById<Button>(R.id.btnStart)
val tv = findViewById<TextView>(R.id.tv1)
// Button onClick action
btn.setOnClickListener{
// Converting Edit Text input to String
val stringTime= (et.text).toString()
// Converting stringTime to Integer
val intTime= Integer.parseInt(stringTime)
// Declaring Main Thread
Thread(Runnable {
// For loop Decrement
for (i in intTime downTo 0) {
// Updating Text View at
// current iteration
runOnUiThread{
tv.text = i.toString()
}
// Thread sleep for 1 sec
Thread.sleep(1000)
}
}).start()
}
}
}
Output:
Similar Reads
How to Send SMS in Android using Kotlin? SMS Manager is a class in Android which is used to send the SMS to a specific contact from the android application. We can send text messages, data messages, and multimedia messages using this class. There are different methods that are provided to send different types of messages. In this article,
4 min read
Implement Universal Image Loader Library in Android using Kotlin Universal Image Loader library is also referred to as (UIL). It is similar to Picasso and Glide which is used to load the images from the URL within our image view inside our android application. This image loading library has been created to provide a powerful, flexible, and customizable solution t
4 min read
Android - Login and Logout Using Shared Preferences in Kotlin Using Shared Preferences We can store data locally on our Android applications. In your Android app if you are using a feature of Login then you should have to save the state if the user has signed the first time. Then when the user closes his app and reopens it then he should redirect to our Home s
6 min read
MultiThreading in Android with Examples Working on multiple tasks at the same time is Multitasking. In the same way, multiple threads running at the same time in a machine is called Multi-Threading. Technically, a thread is a unit of a process. Multiple such threads combine to form a process. This means when a process is broken, the equiv
3 min read
Design Patterns in Android with Kotlin Design patterns is basically a solution or blueprint for a problem that we get over and over again in programming, so they are just typical types of problems we can encounter as programmers, and these design patterns are just a good way to solve those problems, there is a lot of design pattern in an
5 min read
JSON Parsing in Android Using Volley Library with Kotlin JSON is a JavaScript object notation which is a format to exchange the data from the server. JSON stores the data in a lightweight format. With the help of JSON, we can access the data in the form of JsonArray, JsonObject, and JsonStringer. In this article, we will specifically take a look at the im
5 min read
How to Build a Simple Torch App in Android using Kotlin? Torch Application is a very basic application that every beginner level android developer should definitely try to build while learning Android. In this article, we will be creating an application in which we will simply display a toggle button to switch on and switch off the torch. Note: If you are
4 min read
Thread Priority in Android Every thread in a process has a Priority. They are in the range of 1 to 10. Threads are scheduled according to their priorities with the help of a Thread Scheduler. There can be 3 priority constant set for a Thread which are:MIN_PRIORITY which equals to 1MAX_PRIORITY which equals to 10NORM_PRIORITY
3 min read
Android progress notifications in Kotlin In this tutorial you'll learn how to create a basic Progress Notification (Indeterminate progress indicator and Fixed-duration progress indicator) for Android using Kotlin. Before we begin, let us first understand the components of a Notification in Android. Components of a Notification:Small Icon -
4 min read
Android - Update Data in API using Volley with Kotlin Android applications use APIs to get the data from servers in android applications. With the help of APIs, we can add, read, update and delete the data from our database using APIs. We can use Volley and Retrofit for consuming data from APIs within the android application. In this article, we will t
5 min read