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 .
[Link] Computer
University Science and
Institute EMPOWER
Engineering
of Engineering Department
(UIE)
Processes and threads overview
2
[Link] 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.
[Link] 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:-
[Link] {
// code to run in background thread
}
Java code:-
Thread thread = new Thread(new Runnable() {
@Override public void run() {
// code to run in background thread
}
});
• [Link]();
• Note: It’s recommended to use coroutines in Kotlin instead of Thread, as they are more lightweight and easier to
manage.
[Link] 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.
[Link] 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.
[Link] 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.
[Link] 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.
[Link] 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.
[Link] Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
XML code:-
• <?xml version="1.0" encoding="utf-8"?>
• <LinearLayout
• xmlns:android="[Link]
• 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>
[Link] 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 [Link]
• import [Link]
• import [Link]
• import [Link]
• import [Link]
•
• class MainActivity : AppCompatActivity() {
•
• private lateinit var resultTextView: TextView
•
• override fun onCreate(savedInstanceState: Bundle?) {
• [Link](savedInstanceState)
• setContentView([Link].activity_main)
•
[Link] Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
• // Get reference to start button and result text view
• val startButton = findViewById<Button>([Link].start_button)
• resultTextView = findViewById([Link].result_text_view)
•
• // Set an OnClickListener for the start button
• [Link] {
• 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
• [Link] = result
• }
•
•
[Link] Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
• override fun doInBackground(vararg p0: Void?): String {
• // Perform background task
• try {
• [Link](5000)
• } catch (e: InterruptedException) {
• [Link]()
• }
• return "Task Completed"
• }
• }
• }
[Link] Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
Java code:-
• import [Link];
• import [Link];
• import [Link];
• import [Link];
• import [Link];
• public class MainActivity extends AppCompatActivity {
•
• private TextView resultTextView;
•
• @Override
• protected void onCreate(Bundle savedInstanceState) {
• [Link](savedInstanceState);
• setContentView([Link].activity_main);
[Link] Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
•
• // Get reference to start button and result text view
• Button startButton = findViewById([Link].start_button);
• resultTextView = findViewById([Link].result_text_view);
•
• // Set an OnClickListener for the start button
• [Link](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) {
•
[Link] Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
• // Perform background task
• try {
• [Link](5000);
• } catch (InterruptedException e) {
• [Link]();
• }
• return "Task Completed";
• }
•
• @Override
• protected void onPostExecute(String result) {
• // Update UI with the results
• [Link](result);
• }
• }
• }
[Link] Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
Output:
[Link] 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.
[Link] 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.
[Link] 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 [Link].
• 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
[Link] Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
Four steps
• onPreExecute,
• doInBackground,
• onProgressUpdate, &
• onPostExecute.
[Link] 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
[Link] 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.
[Link] 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.
[Link] Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
References
• [Link]
• [Link]
• [Link]
• [Link]
[Link] Computer
University Science and
Institute Engineering Department
of Engineering (UIE)
THANK YOU
For queries
Email: parveen.e13339@[Link]
[Link] Computer
University Science and
Institute Engineering Department
of Engineering (UIE) 26