0% found this document useful (0 votes)
28 views12 pages

Threads and Handlers

This document provides an overview of threading in Android applications, emphasizing the importance of using separate threads for time-consuming tasks to prevent UI freezing. It explains the role of the main thread in handling user interface interactions and the necessity of using handlers to safely update the UI from background threads. Key rules include never performing UI updates from non-main threads and ensuring that all UI changes are synchronized with the main thread through handlers.

Uploaded by

apheleledube94
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views12 pages

Threads and Handlers

This document provides an overview of threading in Android applications, emphasizing the importance of using separate threads for time-consuming tasks to prevent UI freezing. It explains the role of the main thread in handling user interface interactions and the necessity of using handlers to safely update the UI from background threads. Key rules include never performing UI updates from non-main threads and ensuring that all UI changes are synchronized with the main thread through handlers.

Uploaded by

apheleledube94
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

A Basic Overview of Android Threads

and Thread Handlers

overview of Threads
• Threads are the cornerstone of any multitasking operating system
• Can be thought of as mini-processes running within a main process,
• Their purpose is to enable at least the appearance of parallel execution paths
within applications.

A thread is a lightweight sub-process, it going to do background operations


without interrupt to UI
The Application Main Thread
•When an Android application is first started, the runtime
system creates a single thread in which all application
components will run by default. This thread is generally
referred to as the main thread.
•The primary role of the main thread is to handle the user
interface in terms of event handling and interaction with views
in the user interface.
•Any additional components that are started within the
application will, by default, also run on the main thread.
• Any component within an application that performs a time
consuming task using the main thread will cause the entire
application to appear to lock up until the task is completed.
Thread Handlers
Key rules of Android development
• Never to perform time-consuming operations on the main thread of an application.
• The code within a separate thread must never, under any circumstances, directly
update any aspect of the user interface.
• Any changes to the user interface must always be performed from within the main
thread. The reason for this is that the Android UI toolkit is not thread-safe.

● In the event that the code executing in a thread needs to interact with the user
interface, it must do so by synchronizing with the main UI thread.

● This is achieved by creating a handler within the main thread, which, in turn,
receives messages from another thread and updates the user interface accordingly
A Basic Threading
Example

XML file content


• <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/txtDisplay"
android:layout_alignParentTop="true"
android:layout_alignLeft="@+id/btncClick"
android:layout_alignRight="@+id/btncClick"
android:layout_alignEnd="@+id/btncClick"
android:layout_marginTop="148dp" />

<Button
android:text="Click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="76dp"
android:id="@+id/btncClick"
Java code
•package [Link];

import [Link];

import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
•Once the application is running, touch
the Button, at which point the
application will appear to freeze.

• It will, for example, not be possible to


touch the button a second time and in
some situations the operating system
will, as demonstrated in Figure 2,
report the application as being
unresponsive:
Anything that is going to take time to complete within the buttonClick() method
needs to be performed within a separate thread.

Creating a New Thread


• In order to create a new thread, the code to be executed in that thread needs to be
placed within the Run() method of a Runnable instance.
• A new Thread object then needs to be created, passing through a reference to the
Runnable instance to the constructor.
• Finally, the start() method of the thread object needs to be called to start the thread
running. To perform the task within the buttonClick() method, therefore, the
following changes need to be made:
• package [Link];

import [Link];

import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
}

• When the application is now run, touching the button causes the delay to be
performed in a new thread leaving the main thread to continue handling the user
interface, including responding to additional button presses. In fact, each time the
button is touched, a new thread will be created, allowing the task to be performed
multiple times concurrently.

• A close inspection of the updated code for the buttonClick() method will reveal
that the code to update the TextView has been removed. As previously stated,
updating a user interface element from within a thread other than the main thread
violates a key rule of Android development. In order to update the user interface,
therefore, it will be necessary to implement a Handler for the thread.
Implementing a Thread Handler
• Thread handlers are implemented in the main thread of an application and are
primarily used to make updates to the user interface in response to messages sent
by other threads running within the application’s process.
• Handlers are subclassed from the Android Handler class and can be used either
by specifying a Runnable to be executed when required by the thread, or by
overriding the handleMessage() callback method within the Handler subclass
which will be called when messages are sent to the handler by a thread.
• For the purposes of this example, a handler will be implemented to update the
user interface from within the previously created thread.

……………………
public class MainActivity extends AppCompatActivity {
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg)
{
TextView txt_Display =
(TextView)findViewById([Link]);
txt_Display.setText("Button Clicked");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
• The above code changes have declared a handler and implemented
within that handler the handleMessage() callback which will be called
when the thread sends the handler a message. In this instance, the code
simply displays a string on the TextView object in the user interface.

• All that now remains is to modify the thread created in the


buttonClick() method to send a message to the handler when the delay
has completed:

public void btnClick(View view) {


Runnable runnable = new Runnable() {
@Override
public void run() {
long endTime = [Link]() + 20 * 1000;
while ([Link]() < endTime)
{synchronized (this)
{
try
{ wait(endTime - [Link]());
}catch (Exception e)
{
}
}
Note that the only change that has been made is to make a call to the
sendEmptyMessage() method of the handler. Since the handler does not currently
do anything with the content of any messages it receives it is not necessary to
create and send a message object to the handler.

Compile and run the application and, once executing, touch the button. After a 20
second delay, the new text will appear in the TextView object in the user interface.

Passing a Message to the Handler


• While the previous example triggered a call to the handleMessage() handler
callback, it did not take advantage of the message object to send data to the
handler.
• In this phase , the example will be further modified to pass data between the
thread and the handler.
• First, the updated thread in the buttonClick() method will obtain the date and time
from the system in string format and store that information in a Bundle object.
• A call will then be made to the obtainMessage() method of the handler object to
get a message object from the message pool.
• Finally, the bundle will be added to the message object before being sent via a
call to the sendMessage() method of the handler object:
Modify the code as follows
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link]; // Use androidx
import [Link];
import [Link];

import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {


Handler handler = new Handler([Link]()){
@Override
public void handleMessage(Message msg) {
Bundle bundle = [Link]();
String string = [Link]("myKey");
TextView txt_Display = (TextView)findViewById([Link]);
txt_Display.setText(string);
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
}
public void btnClick(View view) {
Runnable runnable = new Runnable() {
@Override
public void run() {
Message msg = [Link]();
Bundle bundle = new Bundle();
SimpleDateFormat dateformat = new SimpleDateFormat
("yyyy/MM/dd HH:mm:ss", [Link]);
String dateString = [Link](new Date());
[Link]("myKey", dateString);
[Link](bundle);
[Link](msg);
}
};
Thread myThread = new Thread(runnable);
[Link]();
}
}

• update the handleMessage()


method of the handler is to extract
the date and time string from the
bundle object in the message and
display it on the TextView object:
• The goal of this section has beenSummary
to provide an overview of threading within
Android applications.
• When an application is first launched in a process, the runtime system creates a
main thread in which all subsequently launched application components run by
default.
• The primary role of the main thread is to handle the user interface, so any time
consuming tasks performed in that thread will give the appearance that the
application has locked up.
• It is essential, therefore, that tasks likely to take time to complete be started in a
separate thread.
• Because the Android user interface toolkit is not thread-safe, changes to the user
interface should not be made in any thread other than the main thread.
• User interface changes can be implemented by creating a handler in the main
thread to which messages may be sent from within other, non-main threads.

You might also like