Since Android SDK 1.5, there is a specific class for handling UI tasks asynchronously:
AsyncTask. You can find its description and usage at Asynchronous tasks using AsyncTask. However, one may need to implement applications with API levels previous to SDK 1.5 and use asynchronous tasks. For that, one needs to implement Threads manually and also handle cases where the UI must be updated while this asynchronous task is being executed.
Using the Code
Firstly, one must be aware that UI updates are only allowed in the main thread, where the UI life-cycle methods are executed. Therefore, one cannot simply start a separate Thread from the UI main thread and update interface elements. For that, a special mechanism is required. In order to do so, one must:
- Start a separate Thread.
- Execute all expense jobs in the
run() method of the started
- When one needs to update the UI, within the separate Thread, one needs to call the
sendMessage(Message) method of a special
Handler comes from the package
android.os.Handler. Within the
sendMessage(Message) method one can, and should, update the required UI elements.
Below is the code which executes what is stated above:
public class MainActivity extends Activity
private ProgressBar mProgress;
private int mProgressStatus = 0;
public void onCreate(Bundle savedInstanceState)
mProgress = (ProgressBar) findViewById(R.id.progressBar);
Thread lenghtyTask = new Thread(new BackgroundThread());
private final class BackgroundThread implements Runnable
public void run()
while (mProgressStatus < 10)
mProgressStatus = doWork();
private Handler mHandler = new Handler()
public void handleMessage(android.os.Message msg)
if (mProgressStatus < 10)
private int counter = 0;
private int doWork()
} catch (InterruptedException e)
The code above executes what was stated in the steps just mentioned. The lengthy Thread is started (step 1). Within it, an expensive job is performed and the progress bar status is returned (step 2). After that, the
sendEmptyMessage(int) is called. This method belongs to the handler
mHandler. This handler simply updates a Progress Bar while a counter is
10. After that, the Progress bar stops (step 3).
As you can see, the mechanism for executing an asynchronous task while updating a UI is not much complicated, as long as you know how to do it correctly.