Using Threads and Handlers

When you want to control a thread yourself, you can use the Thread class in conjunction with a Handler object.

The style of networking that has been presented so far causes the thread it's running on to block until the operation is finished. For small tasks, this might be acceptable. However, when timeouts or additional processing time is needed, such as parsing XML, you need to move these time-intensive operations away from the main UI thread by launching a new thread. This provides a smoother experience for the user.

The following code demonstrates how to create and launch an anonymous thread that connects to a remote server, retrieves and parses some XML, and posts a response back to the UI thread, using a Handler object on the main thread to change a TextView control called parsingStatus, which displays the parsing status:

import android.os.Handler; Handler mHandler = new Handler(); // ...

// Instantiate XML parser mHandler.post(new Runnable() { public void run() {

parsingStatus.setText("Began Parsing...");

// XML Parsing loop here

// Update parsingStatus has needed...

mHandler.post(new Runnable() { public void run() {

parsingStatus.setText("Finished parsing...");

The Thread class uses the Handler object called mHandler to post information back to the main UI thread.

0 0

Post a comment