THREADS
Threads are the foundation of any multitasking operating system which can be visualized as many mini-processes running within a main process, in-order to achieve parallel execution paths within applications.
The Application Main Thread
When an Android application is first booted, by default the run-time system creates a single thread under which all application components will run. This thread is called main thread. The primary role of the main thread is to handle the user interface i.e event handling and interaction among the views in the user interface. Any additional components that can be added to the android application will also be run under the main thread.
Any component which leads to a time consuming task within the application will cause the entire application to run in a lock-up until that task is completed thus displaying “Application is unresponsive” warning to the user which is not a desired behavior of any application. Such a situation can be avoided by launching the task in a separate thread and allowing the main thread to continue unhindered.
Thread Handlers
Key rules of application development are:
• Time-consuming applications on the main thread should not be performed.
• The code within the separate thread must never ever affect the user-interface.
This implies that, any changes to the user-interface must always be performed within the main thread. The reason for this is that the Android User-Interface toolkit is not thread-safe. Attempts to work with non thread-safe code from within multiple threads will typically result in recurrent problems and impulsive application behavior.
In order to update the user-interface accordingly, a thread handler is created within the main thread which in turn receives messages from another thread and interacts with the user-interface.