Wednesday, June 9, 2010

Android threads - the basics

Often you have a need to spawn a thread in which to do something useful, like load data from an external API.

You can handle events from the spawned thread and alert the user. In this case we'll use a ProgressDialog while at work...

Here are the basics. First your class must implement Runnable:
public class FooClass extends Activity implements Runnable {

When you are ready to create the thread:

public void loadData() {
pd =, "Working..", "Accessing data...", true,
Thread thread = new Thread(this);

Then your code is in the run() method:

public void run() {
// do something time intensive or asynchronous

private Handler handler = new Handler() {
public void handleMessage(Message msg) {
pd.dismiss(); // dismiss the progress dialog

The Handler override method handles the end of the thread.
That's it.

No comments:

Post a Comment