Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can only the UI thread in Android update the UI?

Could someone please explain to me why only the UI thread in Android can update the UI? Why can't any other thread update the UI?

like image 775
Dhiral Pandya Avatar asked Oct 12 '11 16:10

Dhiral Pandya


2 Answers

Documentation states that Android UI toolkit is not thread-safe. Thus, single thread model ensures UI is not modified by different threads at the same time.

like image 134
Caner Avatar answered Sep 21 '22 04:09

Caner


As stated on the android developper guide about Thread :

When your app performs intensive work in response to user interaction, this single thread model can yield poor performance unless you implement your application properly. Specifically, if everything is happening in the UI thread, performing long operations such as network access or database queries will block the whole UI. When the thread is blocked, no events can be dispatched, including drawing events. From the user's perspective, the application appears to hang. 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. The user might then decide to quit your application and uninstall it if they are unhappy.

Additionally, the Andoid UI toolkit is not thread-safe. So, you must not manipulate your UI from a worker thread—you must do all manipulation to your user interface from the UI thread. Thus, there are simply two rules to Android's single thread model:

Do not block the UI thread Do not access the Android UI toolkit from outside the UI thread

like image 24
Dimitri Avatar answered Sep 18 '22 04:09

Dimitri