Saturday, November 16, 2024
Google search engine
HomeLanguagesJavaWhat are Threads in Android with Example?

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.

Kotlin




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


Java




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:

  • The main thread, also known as the UI thread, is responsible for handling all UI updates and user interactions. Any code that updates the UI or interacts with the user should be run on the main thread.
  • Worker threads are used for background tasks that should not block the main thread, such as network requests, database operations, and image processing.
  • AsyncTask is a helper class that allows you to perform background tasks and update the UI from the same thread. However, it has some limitations and it’s recommended to use coroutines or other libraries for more complex tasks.
  • Services are used for tasks that should continue running even when the app is not visible, such as playing music or downloading files.
  • In addition to the above, there are other types of threading mechanisms available in android such as IntentService, JobIntentService, Service, JobScheduler, and AlarmManager.

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




<?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.

Kotlin




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"
        }
    }
}


Java




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:

 

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments