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

Android Threads Processes

The document discusses Android processes and threads. By default, all components of an Android application run in the same process and thread. Slow operations should be done in worker threads to avoid slowing the UI. Additional threads can be created and different components can run in separate processes. The AsyncTask class simplifies performing asynchronous tasks that interact with the UI.

Uploaded by

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

Android Threads Processes

The document discusses Android processes and threads. By default, all components of an Android application run in the same process and thread. Slow operations should be done in worker threads to avoid slowing the UI. Additional threads can be created and different components can run in separate processes. The AsyncTask class simplifies performing asynchronous tasks that interact with the UI.

Uploaded by

mcutechnologies
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

CSE 5343/7343

Android Processes and Threads

Quickview
• Every application runs in its own process and all components of the application run in
that process, by default
• Any slow, blocking operations in an activity should be done in a new thread, to avoid
slowing down the user interface

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

However, you can arrange for different components in your application to run in separate
processes, and you can create additional threads for any process.

Processes
By default, all components of the same application run in the same process and most applications
should not change this.

Android might decide to shut down a process at some point, when memory is low and required
by other processes that are more immediately serving the user. Application components
running in the process that's killed are consequently destroyed. A process is started again for
those components when there's again work for them to do.

When deciding which processes to kill, the Android system weighs their relative importance to
the user. For example, it more readily shuts down a process hosting activities that are no longer
visible on screen, compared to a process hosting visible activities. The decision whether to
terminate a process, therefore, depends on the state of the components running in that process.

Threads
When an application is launched, the system creates a thread of execution for the application,
called "main." This thread is very important because it is in charge of dispatching events to the
appropriate user interface widgets, including drawing events. It is also the thread in which your
application interacts with components from the Android UI toolkit (components from the
android.widget and android.view packages). As such, the main thread is also sometimes
called the UI thread.

The system does not create a separate thread for each instance of a component. All components
that run in the same process are instantiated in the UI thread, and system calls to each component
are dispatched from that thread. Consequently, methods that respond to system callbacks (such
as onKeyDown() to report user actions or a lifecycle callback method) always run in the UI
thread of the process.

For instance, when the user touches a button on the screen, your app's UI thread dispatches the
touch event to the widget, which in turn sets its pressed state and posts an invalidate request to
the event queue. The UI thread dequeues the request and notifies the widget that it should redraw
itself.

When your app performs intensive work in response to user interaction, this single thread model
can yield poor performance unless you implement your application properly. Specifically, if
everything is happening in the UI thread, performing long operations such as network access or
database queries will block the whole UI.

When the thread is blocked, no events can be dispatched, including drawing events. From the
user's perspective, the application appears to hang. Even worse, if the UI thread is blocked for
more than a few seconds (about 5 seconds currently) the user is presented with the infamous
"application not responding" (ANR) dialog. The user might then decide to quit your application
and uninstall it if they are unhappy.

Additionally, the Andoid UI toolkit is not thread-safe. So, you must not manipulate your UI from
a worker thread—you must do all manipulation to your user interface from the UI thread. Thus,
there are simply two rules to Android's single thread model:

1. Do not block the UI thread


2. Do not access the Android UI toolkit from outside the UI thread

Worker threads

Because of the single thread model described above, it's vital to the responsiveness of your
application's UI that you do not block the UI thread. If you have operations to perform that are
not instantaneous, you should make sure to do them in separate threads ("background" or
"worker" threads).

For example, below is some code for a click listener that downloads an image from a separate
thread and displays it in an ImageView:

public void onClick(View v) {


new Thread(new Runnable() {
public void run() {
Bitmap b = loadImageFromNetwork("http://example.com/image.png");
mImageView.setImageBitmap(b);
}
}).start();
}

At first, this seems to work fine, because it creates a new thread to handle the network operation.
However, it violates the second rule of the single-threaded model: do not access the
Android UI toolkit from outside the UI thread—this sample modifies the ImageView
from the worker thread instead of the UI thread. This can result in undefined and unexpected
behavior, which can be difficult and time-consuming to track down.

To fix this problem, Android offers several ways to access the UI thread from other threads. Here
is a list of methods that can help:

• Activity.runOnUiThread(Runnable)
• View.post(Runnable)
• View.postDelayed(Runnable, long)

For example, you can fix the above code by using the View.post(Runnable) method:

public void onClick(View v) {


new Thread(new Runnable() {
public void run() {
final Bitmap bitmap =
loadImageFromNetwork("http://example.com/image.png");
mImageView.post(new Runnable() {
public void run() {
mImageView.setImageBitmap(bitmap);
}
});
}
}).start();
}

Now this implementation is thread-safe: the network operation is done from a separate thread
while the ImageView is manipulated from the UI thread.

However, as the complexity of the operation grows, this kind of code can get complicated and
difficult to maintain.

Perhaps the best solution, though, is to extend the AsyncTask class, which simplifies the
execution of worker thread tasks that need to interact with the UI.

Using AsyncTask

AsyncTask allows you to perform asynchronous work on your user interface. It performs the
blocking operations in a worker thread and then publishes the results on the UI thread, without
requiring you to handle threads and/or handlers yourself.
To use it, you must subclass AsyncTask and implement the doInBackground() callback
method, which runs in a pool of background threads. To update your UI, you should implement
onPostExecute(), which delivers the result from doInBackground() and runs in the UI thread,
so you can safely update your UI. You can then run the task by calling execute() from the UI
thread.

For example, you can implement the previous example using AsyncTask this way:

public void onClick(View v) {


new DownloadImageTask().execute("http://example.com/image.png");
}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {


/** The system calls this to perform work in a worker thread and
* delivers it the parameters given to AsyncTask.execute() */
protected Bitmap doInBackground(String... urls) {
return loadImageFromNetwork(urls[0]);
}

/** The system calls this to perform work in the UI thread and delivers
* the result from doInBackground() */
protected void onPostExecute(Bitmap result) {
mImageView.setImageBitmap(result);
}
}

Now the UI is safe and the code is simpler, because it separates the work into the part that should
be done on a worker thread and the part that should be done on the UI thread.

You might also like