message

How to run background jobs using threads

SDK Version: 
M3

Previously I wrote about, that slow operations must be runned in threads. Now I would like to present some example code, how to use threads in Android.

Under the android system an user interface element can only be accessed from the thread that created it (the main UI thread). Thats where handlers and messages come in.

The user interface defines a handler like below:

  1. Handler handler = new Handler() {
  2.   @Override
  3.   public void handleMessage(Message msg) {
  4.     int arg1=msg.arg1;
  5.     int arg2=msg.arg2;
  6.     MyClass myObject=(MyClass)msg.obj;
  7.     //do something in the user interface to display data from message
  8.   }
  9. }

Then the thread, which can not touch the user interface, sends a message to this handler instead.

The following example code, that implements file downloading from net, represents how I usually use the threads:

  1. public class Downloader {
  2.   Thread thread=null;
  3.   boolean interrupted=false;

Syndicate content