0% found this document useful (0 votes)
16 views

Lecture 1.3.5

This document provides an overview of threads and asynchronous tasks in Android. It discusses how threads allow background processes to run independently of the main UI thread. It also covers AsyncTask and services for asynchronous operations. Finally, it outlines the steps to implement threads in Android, including setting up the project files and code for a basic threading example.

Uploaded by

Arzoo Chhabra
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Lecture 1.3.5

This document provides an overview of threads and asynchronous tasks in Android. It discusses how threads allow background processes to run independently of the main UI thread. It also covers AsyncTask and services for asynchronous operations. Finally, it outlines the steps to implement threads in Android, including setting up the project files and code for a basic threading example.

Uploaded by

Arzoo Chhabra
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

INSTITUTE : UIE

DEPARTMENT : CSE
Bachelor of Engineering (Computer Science &
Engineering)
Mobile Application Development(21CSH-355/21ITH-355)

TOPIC OF PRESENTATION:
Threads overview and Asynchronous Tasks
Prepared by:
Parveen Kumar Saini(E13339)

DISCOVER . LEARN .
www.cuchd.in Computer
University Science and
Institute EMPOWER
Engineering
of Engineering Department
(UIE)
Processes and threads overview

2
www.cuchd.in Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
Processes and threads overview
• When an application component starts and the application does not have any other
components running, the Android system starts a new Linux process for the
application with a single thread of execution.
• By default, all components of the same application run in the same process and
thread (called the "main" thread).
• If an application component starts and there already exists a process for that
application (because another component from the application exists), then the
component is started within that process and uses the same thread of execution.
• However, you can arrange for different components in your application to run in
separate processes, and you can create additional threads for any process.

www.cuchd.in Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
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 Code:-
GlobalScope.launch {
// code to run in background thread
}
Java code:-
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.
www.cuchd.in Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
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.

www.cuchd.in Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
AsyncTask and Services
• 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.

www.cuchd.in Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
Important point to be consider for threads
• 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.

www.cuchd.in Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
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.

www.cuchd.in Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
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.

www.cuchd.in Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
XML code:-

• <?xml version="1.0" encoding="utf-8"?>


• <LinearLayout
• xmlns:android="http://schemas.android.com/apk/res/android"
• 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>

www.cuchd.in Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
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 code:-
• 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)

www.cuchd.in Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
• // 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
• }

www.cuchd.in Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
• override fun doInBackground(vararg p0: Void?): String {
• // Perform background task
• try {
• Thread.sleep(5000)
• } catch (e: InterruptedException) {
• e.printStackTrace()
• }
• return "Task Completed"
• }
• }
• }
www.cuchd.in Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
Java code:-

• 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);
www.cuchd.in Computer
University Science and
Institute Engineering Department
of Engineering (UIE)

• // 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) {

www.cuchd.in Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
• // 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);
• }
• }
• }

www.cuchd.in Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
Output:

www.cuchd.in Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
Asynchronous Tasks in Android:-
• AsyncTask is an abstract class in Android that offers us the freedom to execute
demanding tasks in the background while keeping the UI thread light and the
application responsive.
• When launched, an Android application operates in a single thread.
• Due to this single-thread approach, tasks that take a long time to fetch a response
may cause the program to become unresponsive.
• We use Android AsyncTask to perform these heavy tasks in the background on a
separate thread and return the results back to the UI thread in order to prevent this.
• As a result, the UI thread is always responsive when AsyncTask is used in an
Android application.

www.cuchd.in Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
The purpose of AsyncTask
• The purpose of AsyncTask was to make it possible to use the UI thread correctly
and conveniently.
• The most frequent use case, however, was UI integration, which led to Context
leaks, missed callbacks, or crashes when settings changed.
• Additionally, it behaves differently depending on the platform version, swallows
exceptions from do In Background, and offers little benefit over using Executors
directly.

www.cuchd.in Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
The purpose of AsyncTask
• Async Task is not intended to be a general-purpose threading system; rather, it is
intended to be a helper class for Thread and Handler.
• Async Tasks are best used for brief operations (a few seconds at the most.) It is
strongly advised that you use the various APIs offered by the java.util.
• Concurrent package, such as Executor, Thread Pool Executor, and FutureTask, if
you need to keep threads running for extended periods of time.
• Asynchronous tasks are divided into three generic types:
• Params, Progress, & Result

www.cuchd.in Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
Four steps
• onPreExecute,
• doInBackground,
• onProgressUpdate, &
• onPostExecute.

www.cuchd.in Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
The following lists the three generic types utilized in an Android AsyncTask
class:

• Params: Parameters sent to the task upon execution


• Progress: Progress units shared during the background computation
• Result: Result obtained from the background computation

www.cuchd.in Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
The following definitions outline the fundamental methods used in an Android
AsyncTask class:

• doInBackground(): The code that has to be run in the background is contained in


the doInBackground() method.
• The publishProgress() method in this method allows us to repeatedly deliver
results to the UI thread.
• We only need to use the return statements to signal that the background processing
has been finished.

www.cuchd.in Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
The following definitions outline the fundamental methods used in an Android
AsyncTask class:
• onPreExecute(): The code that runs prior to the beginning of the background
processing is contained in this function.
• onPostExecute(): After the doInBackground method has finished processing, the
onPostExecute() method is called.
• This method receives the output of the doInBackground method as its input.
• onProgressUpdate(): This method can use the progress updates it receives from the
publishProgress method, which publishes progress updates from the
doInBackground function, to update the UI thread.

www.cuchd.in Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
References
• https://developer.android.com/guide/components/processes-and-threads
• https://www.geeksforgeeks.org/what-are-threads-in-android-with-example/
• https://developer.android.com/guide/components
• https://www.geeksforgeeks.org/asynctasks-in-android/

www.cuchd.in Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
THANK YOU

For queries
Email: [email protected]

www.cuchd.in Computer
University Science and
Institute Engineering Department
of Engineering (UIE) 26

You might also like