Android – Threads Tutorial

Today we are going to talk about Threads in Android. I assume we all know what Threads are, what they do and where we can use them. Also I assume we know the basic Android applications, what Activities are and how we’re usually dealing with them. If not, take a little time to get used to them on the official development site.

We have a few things to understand about Threads usage in Android:

  • They act much like usual Java Threads
  • They can’t act directly on external User Interface objects (they throw the Exception CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views”). A Handler from the view hierarchy owner must be used for interpreting and executing all actions for the Thread
  • They can change non-visual objects from their scope, but synchronization issues need to be taken care of
  • They are started by running <thread>.start() – do not think that because you’ve implemented its run() method you should explicitly call it. If you want the Thread to be executed parallel to the main process, it must be started by <thread>.start()
  • They can’t be stopped by executing destroy() nor stop(). Use instead interrupt() or join() (by case)

We’ll take a look at three situations while gradually learning some Thread practices: an Activity class implementing Runnable interface to gain Thread behavior, a Thread contained in a class (and even more, a method of that class), an independent Thread used by an Activity.

One last important note – don’t mind too much all the comments in the code, they are there to give you directions when learning, not to be used further. I overused them in these listings to be sure that each part of the programs is well understood, but remember not to code the same way in real life.

Example – Class Implementing Runnable Interface

We start with simple things. This little application just displays a text and changes it after 3 seconds.

The Activity is prepared, displayed on the device screen and the Thread starts. The Thread has no loop, it waits for 3 seconds, notifies the Handler Object and finishes. The Handler just replaces the text we see on the screen with the new one, no matter what kind of notification (message) the Thread sends. That’s all.

Application views

Application view before and after Thread action

Let’s see the basic form of the code we need to understand:

public class SomeClass [extends Activity] implements Runnable{
    public void someMethod(…){
	    // ...
	    // initializing and starting a new local Thread object
	    Thread currentThread = new Thread(this);
	    currentThread.start();
        // or even initializing and starting like this
        // new Thread(this).start();
        // ...
    }

    // method executed by the Thread
    @Override
    public void run() {
        // all the stuff we want our Thread to do goes here
    }

    // manages Threads messages
    private Handler threadHandler = new Handler() {
	    public void handleMessage(android.os.Message msg) {
    	    // handling messages and acting for the Thread goes here
        }
    };

    // ...
    // other methods
}

And now the whole thing:

public class TestMain extends Activity implements Runnable{

    // text view influenced by the Thread
    private TextView threadModifiedText;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        threadModifiedText =
            (TextView) findViewById(R.id.thread_modified_text);

        // initializing and starting a new local Thread object
        Thread currentThread = new Thread(this);
        currentThread.start();
    }

    // Method you must override to control what the Thread is doing
    @Override
    public void run() {
        try {
            // all the stuff we want our Thread to do goes here
            Thread.sleep(3000);
            // signaling things to the outside world goes like this
            threadHandler.sendEmptyMessage(0);
        } catch (InterruptedException e) {
            //don't forget to deal with the Exception !!!!!
        }
    }

    // Receives Thread's messages, interprets them and acts on the
    // current Activity as needed
    private Handler threadHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            // whenever the Thread notifies this handler we have
            // only this behavior
            threadModifiedText.setText("my text changed by the thread");
        }
    };

}
  • Notice the use of a try-catch block in the run() method as some functions in the Thread class can throw Exceptions. Don’t forget to manage Exceptions! A background Thread that “goes wild” can cause great trouble
  • Thread.sleep() method can throw InterruptedException
  • Notice that the Handler acts the same for any message value sent by the Thread
  • As we don’t use currentThread later in the code, we can also start it with something like this – new Thread(this).start();

You can access the source code for this example here.

I hope this helped. In the Threads Tutorial – Part 2 we’ll deal with a Thread inside a method and we will learn some things about loops, messages and stopping Threads.

124 comments

  1. Nice Example

  2. Austin Canfield

    Very nice tutorial for somebody who has never worked with threads. One thing I’m not quite clear on, though is how I can send different messages to the handler and set up the handler to do different things for each kind of message.

  3. Whoo hoo!! very nice. will use it and to launch a activity from the thread so that my from UI animation keeps playing. hope it all goes well.

    android 8cupsaday app coming soon!

  4. whitetiger

    nice tutorial for someone who is new to thread..thanks you very much!

  5. Nice Example it will useful for me.

  6. Nice post,

    I just would like to know, what will happen if I move to another activity class, is the thread still alive?

    Thanks

  7. o khotya aye ki chawli a?

  8. nice tutorial

  9. Rudresha

    Hey Superb code and easy to understand

  10. nice tutorial
    i am working on threads
    i would like to know if it possible to start thread in one activity and stop that thread in another activity if its possible please post the code

  11. Your examples are very usefull and simple, thank you very much

  12. Great, finally i got my threads running

  13. Thank you! Very nice example!

  14. Thank you, it is very clear

  15. really nice tutorial, thanks for your work!!!

Trackbacks/Pingbacks

  1. Android – Threads Tutorial – Part 2 | IndyVision.Net - [...] providing a class implementing Runnable in the Threads constructor (and that class needs to implement the run() method) – ...

Leave a Reply

You must be logged in to post a comment.