Using Threads Tutorial

  • Written by  Clive

Forget the grass, get off the Main thread!

Android threads tutorial icon

Have you read the article on Processes and Threads yet?

Always remember the two most important rules when working with threads:

  • Don’t block the Main thread
  • Don’t try and access the UI directly from the worker thread

Speed up your apps response times. Move all processing and I/O operations off the main thread. Do the work in a child thread. Our tutorial will show you how.

Our Tutorial app

Our tutorial app has two activities.

We use the first to run two threads. The first thread starts when the app starts. It simulates doing some work off the main thread for 2 seconds. It does not interact with the User Interface.

The second thread starts with a button press. It simulates downloading an image off the main thread. It needs to access the UI to display the downloaded image.

Threads Tutorial app screenshots

The first activity’s on the left. Pressing the Next button starts the second activity, on the right

The second activity starts a thread when a button is pressed. It does some simulated work off the main thread and when it’s finished, passes some data to the main thread for display. We’ll use a Handler to do this.

Both activities have a counter button. Pressing this displays a counter that increases with each button press. This demonstrates that the app is responsive while processing continues in the worker thread.

The First Activity

New kid on the block: The Simple Child Thread

This is a simple worker thread that does some work off the main thread. It does not interact with the UI.

It’s started in the activity’s onCreate method when the activity is first created. The user is able to interact with the app while the thread is running. You can test this by pressing the counter button.

When the thread has finished its work, it sets the counter to 1000. This will show as 1001 when the counter button is next pressed.

In the activity’s onCreate method we have the following code:

A simple worker thread code

Starting our worker thread

Note the following:

  • The MainActivity implements the Runnable interface. We must include its run() method in the activity
  • simpleThread – we construct a new Thread with the activity class as the parameter (the Runnable object)
  • setDaemon – this sets the thread to be a daemon thread which will be killed by the system when the main thread is killed
  • start – we start the thread and it starts its work

Here’s the code for the run() method:

Setting the thread priority

Setting the priority of the thread

Note the following:

  • android.os.Process – this gives us access to the tools for managing the Process. This allows us to fine tune the thread priority with its range (-20 to 19). We can also set the priority of the Thread using setPriority(). These settings range from highest priority 10, to lowest at 1
  • setThreadPriority – many threads can run at the same time. By giving a thread a higher priority means it is executed before threads having a lower priority. We set our thread to background priority which is slightly lower than normal priority. Doing this makes sure that it will be unlikely to affect the UI
  • goToSleep – a call to the goToSleep() method which is basically a 2 second delay (simulating work)
  • counter – once the work is finished, we set the counter to 1000. It will display on screen when the counter button is pressed so that the user can see that the thread has completed its work

Your cheque is in the mail: Using Post to update the UI

Our second thread starts with a button press. It simulates downloading an image off the main thread. The image is then displayed in the UI. A Toast message is also shown.

This thread has to be able to interact with the UI.

Here’s the code that executes when the button is pressed:

Update the UI using post

Using post to update the User Interface

Note the following:

  • myThread – we create a new thread with a new Runnable as its parameter
  • run() – the first run() method starts the download off the main thread by calling the downloadImage() method. The method returns the downloaded drawable
  • post – the Runnable will be added to the message queue and will run on the UI thread
  • run() – the second run() method executes on the UI thread. It is therefore able to display a Toast message and the downloaded image
  • start – starts the thread
Downloading the image

We simulate downloading an image with the downloadImage() method. Here’s the code:

Dummy image download method

Simulating downloading an image

Note the following:

  • goToSleep – a call to the goToSleep() method which is basically a 2 second delay (simulating work)
  • our image is in the res/drawable-mdpi folder. We use getResources() and getDrawable() to get it and assign it to the drawable object, drawableImage which is returned

The Second Activity

Here we use a Handler to display a message sent from a worker thread.

In this activity we start a thread by pressing a button.

We want to display a text message when the thread has completed its work. We can’t do this from the worker thread so we send the message to a handler. The handler is then able to interact with the UI and display the message.

The Butler did it: Using a Handler to update the UI

An app’s main thread runs a message queue that manages activities, broadcast receivers, etc. You can send messages to this queue from another thread by using a Handler. The messages are queued in the Handler and processed when appropriate (either as soon as the queue is ready to do so, after a delay or at a specified time).

Our handler will receive a message sent by the worker thread when it has finished its work.

The Handler

Here’s how we set up the Handler:

Create the message Handler

Create the Handler associated with the Main thread

Note the following:

  • handler – we construct a new Handler. This Handler is now associated with the main thread’s message queue. It allows us to send messages to this queue from the worker thread. It also processes these messages
  • handleMessage – this method will receive the message sent from the worker thread. Its parameter is a Message object which contains the data sent by the worker thread
  • bundle – the data in the Message object is contained in a Bundle. Have a look at the tutorial, Passing data between activities for more on bundles
  • message – we get the message String out of the bundle using getString()
  • setText – we display the message in the text view
Starting the thread

Here’s the code that executes when the button is pressed to start the thread:

Sending a message to the Handler

Start the thread that sends a message to the Handler

Note the following:

  • aRunnable – we create a new Runnable interface object
  • run() – this method executes when the thread starts
  • goToSleep – a call to the goToSleep() method which is basically a 2 second delay (simulating work)
  • msg – our Message object (we’ll put our message that we want displayed into this object)
  • handler – our Handler object
  • obtainMessage – this gives us a new Message object that we can use
  • bundle – a Bundle object into which we will put our message String. Have a look at the tutorial, Passing data between activities for more on bundles
  • threadMessage – the message that we will pass on to the handler when the thread has finished its work
  • putString – we put the string into the bundle
  • setData – puts the bundle into the Message object
  • sendMessage – puts our message in the message queue which will be received by our handler
  • aThread – we create a new Thread passing our Runnable as the parameter
  • start – starts the thread and executes the Runnable

You may also be interested in these articles, where Android takes care of common tasks that are run off the main thread:

I hope that you have found this tutorial helpful.

Please consider subscribing to our notification email. We’ll send you one email on Friday with links to our latest tutorials. That way you won’t miss out. If we didn’t publish any then we won’t send any email. No spam. 

This tutorial was created using Android Studio. You can download the project files here Download icon

Are you using Eclipse or another IDE? Here's how you can use this project's Android Studio files.