Open In App

What are Threads in Android with Example?

In Android, a thread is a background process that can run independently of the main UI thread. In Java and Kotlin, the Thread class and coroutines can be used to create and manage threads.




GlobalScope.launch {
    // code to run in background thread
}




Thread thread = new Thread(new Runnable() {
    @Override public void run() {
        // code to run in background thread
    }
});
thread.start();

Note: It’s recommended to use coroutines in Kotlin instead of Thread, as they are more lightweight and easier to manage.



Code Snippet of a function that uses coroutines to perform a network request in the background, and updates the UI with the result:

fun doNetworkRequest() = GlobalScope.launch(Dispatchers.Main) {
   val result = withContext(Dispatchers.IO) {
   // perform network request
   }
   // update UI with the result
}

There are different types of threads in Android, each with its own use cases:



It’s important to choose the right threading mechanism for your task to ensure optimal performance and avoid threading issues. It’s also important to test your app thoroughly on different devices and configurations to ensure that it behaves correctly and does not crash due to threading issues.

Step-by-Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.

Step 2: Working with the XML Files

Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">
  
    <!-- Display the result text -->
    <TextView
        android:id="@+id/result_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Result will appear here"
        android:textSize="25sp" />
  
    <!-- Start button -->
    <Button
        android:id="@+id/start_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start" />
    
</LinearLayout>

Step 3: Working with the MainActivity & ExampleIntentService File

Go to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.




import android.os.AsyncTask
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
  
class MainActivity : AppCompatActivity() {
  
    private lateinit var resultTextView: TextView
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // Get reference to start button and result text view
        val startButton = findViewById<Button>(R.id.start_button)
        resultTextView = findViewById(R.id.result_text_view)
  
        // Set an OnClickListener for the start button
        startButton.setOnClickListener {
            BackgroundTask().execute()
        }
    }
  
    // BackgroundTask inner class to perform the background task
    private inner class BackgroundTask : AsyncTask<Void?, Void?, String>() {
        override fun onPostExecute(result: String) {
            // Update UI with the results
            resultTextView.text = result
        }
  
        override fun doInBackground(vararg p0: Void?): String {
            // Perform background task
            try {
                Thread.sleep(5000)
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }
            return "Task Completed"
        }
    }
}




import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
  
public class MainActivity extends AppCompatActivity {
  
    private TextView resultTextView;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Get reference to start button and result text view
        Button startButton = findViewById(R.id.start_button);
        resultTextView = findViewById(R.id.result_text_view);
          
        // Set an OnClickListener for the start button
        startButton.setOnClickListener(view -> new BackgroundTask().execute());
    }
  
    // BackgroundTask inner class to perform the background task
    private class BackgroundTask extends AsyncTask<Void, Void, String> {
        @Override
        protected String doInBackground(Void... voids) {
            // Perform background task
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Task Completed";
        }
  
        @Override
        protected void onPostExecute(String result) {
            // Update UI with the results
            resultTextView.setText(result);
        }
    }
}

Output:

 


Article Tags :