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

一曲冷凌霜 提交于 2019-12-21 05:04:00

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/7743121/why-can-only-the-ui-thread-in-android-update-the-ui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!