Saturday, 15 September 2012

Threading in Android


Android modifies the user interface and handles input events from one single user interface thread which is also called the main thread.If the programmer does not use any concurrency constructs, all code of an Android application runs in this thread.If you perform a long lasting operation, e.g. loading a file or accessing data from the Internet, the user interface of your Android Application will block until the corresonding code has finished.

To provide a good user experience all potentially slow running operations in an Android application should run asynchronously, e.g. via some way of concurrency constructs of the Java language or the Android framework. This includes all potential slow operations, like network, file and database access and complex calculations.

This single thread model can yield poor performance in Android applications that do not consider the implications. Since everything happens on a single thread performing long operations, like network access or database queries, on this thread will block the whole user interface. No event can be dispatched, including drawing events, while the long operation is underway. From the user's perspective, the application appears hung. Even worse, if the UI thread is blocked for more than a few seconds (about 5 seconds currently) the user is presented with the infamous "application not responding" (ANR) dialog.

For this reason we use Handler Threads in Android.In Handler Thread basically there are two components:

1.     Looper

2.     Message Queue.

In Java environment looper is in passive mode but have Message Queue.A given handler have only one looper and one message queue.If anybody wants to communicate with application, they have send a message and push that message into message queue of that handler  thread.

1 comment: