Android Threads, Handlers and AsyncTask

UI Thread and Background Processing

Android modifies the user interface via one thread, the UI Thread. If the programmer does not use any concurrency constructs, all code of an Android application runs in this UI thread. If you perform a long lasting operation the user interface of your Android Application will block until your code has finished.

Therefore all

potentially slow running operations in an Android application should run in the background, e.g. via some way of concurrency constructs of the Java language or the Android framework. Potential slow operations are network, file and database access but also complex calculations.

This tutorial will teach how to use the special Android constructs for concurrency.

Background Processing using Threads & Handlers

Threads

Android supports standard Java Threads. You can use standard Threads and the tools from the package “java.util.concurrent” to put actions into the background. The only limitation is that you cannot directly update the UI from the a background process.

If you need to update the UI from a background task you need to use some Android specific classes. You can use the class “android.os.Handler” for this or the class “AsyncTasks

Handler

The class “Handler” can update the UI. A handle provides methods for receiving messages and for runnables. To use a handler you have to subclass it and override handleMessage() to process messages. To process runables you can use the method post(); You only need one instance of a handler in your activity.

You thread can post messages via the method sendMessage(Message msg) or sendEmptyMessage.

Sample Example

Here in this example we will notify user when for example user click button and in onClick method program starts some long-time process which will do your task in background with the help Handlers.

So create a project named “com.mobisys.android.handler_ex” having “HandlerActivity” in it.

main.xml contains:
[sourcecode language=”xml”]