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 = ProgressDialog.show(this, "Working..", "Accessing data...", true,
false);
Thread thread = new Thread(this);
thread.start();
}

Then your code is in the run() method:

public void run() {
// do something time intensive or asynchronous
handler.sendEmptyMessage(0);
}

private Handler handler = new Handler() {
@Override
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