When an Android program starts running, a process is started separately. By default, all activity or service (service and activity) in this program is only two of the components that Android provides, in addition to content provider and broadcast Receiver) will run in this process.
An Android program has only one process by default, but a process can have a number of thread.
Among so many thread, there is a thread, which we call the UI Thread. The UI thread is created when the Android program is running, and is the main thread of a process that is responsible for controlling the display, update, and control interaction of the UI interface. At the beginning of the Android program, a process presented a single-threaded model, with all tasks running in one thread. Therefore, we think that every function that the UI thread executes should take as short a time as possible. Other more time-consuming work (access to the network, download data, query database, etc.), should be left to the sub-thread to do so as not to block the main thread.
So how does the UI thread work with the other thread? Common methods are:
The handler object, which is the main thread, is created as listener to allow the child thread to push the message into the main thread's message quene in order to trigger the Handlermessage () function of the main thread, let the main thread know the state of the child threads, and update the UI on the main thread.
For example, when the state of a child thread changes, we need to update the UI. If the UI is updated directly in a child thread, the following exception is usually thrown:
11-07 13:33:04.393:error/javabinder (1029): Android.view.viewroot$calledfromwrongthreadexception:only the original Thread that created a view hierarchy can touch it views.
This means that the UI cannot be updated in the child thread. To do this, we need to update the interface by handler objects, notifying the main thread UI thread.
There is also a common problem that we encounter that throws the following exception:
Can ' t create handler inside thread that have not called looper.prepare ()
This means that the handler object is created in a child thread without the associated Looper object.
Main thread and sub-thread of Android