Thread is one of the important concepts in Android. Thread is a lightweight sub-process that provides us a way to do background operations without interrupting the User Interface (UI). When an app is launched, it creates a single thread in which all app components will run by default. The thread which is created by the runtime system is known as the main thread. The main thread’s primary role is to handle the UI in terms of event handling and interaction with views in the UI. If there is a task that is time-consuming and that task is run on the main thread, then it will stop other tasks until it gets completed, which in turn may result in displaying a warning “Application is unresponsive” to the user by the operating system. So we need different threads for such tasks and some other tasks.
All threading components belong to one of two basic categories.
The fragment or activity attached threads: This category of threads are bound to the lifecycle of the activity/fragment and these are terminated as soon as the activity/fragment is destroyed.
Thread components:
AsyncTask, Loaders.
The fragment or activity not attached threads: These types of threads can continue to run beyond the lifetime of the activity or fragment from which they were spawned.
Threading Components: Service, Intent Service.
For the two threading components, there are five types of thread used in Android mobile development.
Main Thread: When we launch our app on Android, it creates the first thread of execution called the “Main Thread”. The communication between the components from the Android UI toolkit and the dispatching of events to their appropriate UI widgets is handled by the main thread. We should avoid network operations, database calls, and the loading of certain components in the main thread. Because the main thread is called synchronously when executed, that means the user interface will remain completely unresponsive until the performance completes.
UI Thread: Every app in Android has its own thread which is responsible for running the UI objects, like view objects. Such a thread is known as the UI thread. The UI thread is the main thread of execution for our app as this is where most of the app code is run. The UI thread is where all of our app components (like activities, services, content providers, and broadcast receivers) are created. This thread allows our tasks to perform their background work and then move the results to UI elements such as bitmaps. All objects running on our UI thread will be able to access other objects which are also running on the same UI thread. The tasks that we run on a thread from a thread pool do not run on our UI thread, so they will not have access to UI objects. The data moves from a background thread to the UI thread, using a handler that runs on the UI thread.
Worker Thread: The worker thread is a background thread. The worker threads are created separately, other than threads like the UI thread. As we know from the rules, we cannot block a UI thread so this is where the worker thread comes into play since we can use them to run the child processes and tasks.
Any Thread:
1
2
3
4
5
6
7
8
@Target([
AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.PROPERTY_SETTER, AnnotationTarget.CONSTRUCTOR,
AnnotationTarget.CLASS, AnnotationTarget.FILE,
AnnotationTarget.VALUE_PARAMETER
])
class AnyThread
Binder Thread: Binder thread represents a separate thread of service. The binder is a mechanism that provides inter-process communication. The binder thread is used in service binding with interprocess communication. This concept is mainly related to service calls with interfaces defined by Android Interface Definition Language (AIDL).
Exampleactivity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center_horizontal" android:layout_marginTop="100dp" tools:context=".MainActivity"> <EditText android:id="@+id/et_query" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter string" /> <Button android:id="@+id/bt_click" android:layout_marginTop="50dp" style="@style/Base.TextAppearance.AppCompat.Widget.Button.Borderless.Colored" android:layout_width="wrap_content" android:background="#c1c1c1" android:textColor="#FFF" android:layout_height="wrap_content" android:text="Button" /> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
MainActiviy.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.example.myapplication;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText et_query;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_query = findViewById(R.id.et_query);
textView = findViewById(R.id.text);
findViewById(R.id.click)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
runthread();
}
});
}
private void runthread() {
final String s1 = et_query.getText()
.toString();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(s1);
}
});
}
}, 5000);
}
}
Output: