最近在开发 Android 项目时,遇到了一个偶尔会出现的 Android ANR keyDispatchingTimedOut Error 错误,在网上搜索过后找到了一个相同问题的帖子,参见
http://stackoverflow.com/questions/4529770/android-anr-keydispatchingtimedout-error-while-continuous-tapping-on-screen,
该帖子遇到的问题正好是我遇到的问题,通读帖子的回答,发现是 Thread 方面的问题,转到 Android 开发官方文档,参见
http://developer.android.com/resources/articles/painless-threading.html,
读完官方文档后即发现了自己的错误所在。
原文如下:
Painless Threading
This article discusses the threading model used by Android applications and how applications can ensure best UI performance by spawning worker threads to handle long-running operations, rather than handling them in the main thread. The article also explains the API that your application can use to interact with Android UI toolkit components running on the main thread and spawn managed worker threads.
The UI thread
When an application is launched, the system creates a thread called"main" for the application. The main thread, also called theUIthread, is very important because it is in charge of dispatching theevents to the appropriate widgets, including drawing events.It is also the thread where your application interacts with running components of the Android UI toolkit.
For instance, if you touch the a button on screen, the UI thread dispatchesthe touch event to the widget, which in turn sets its pressed state andposts an invalidate request to the event queue. The UI thread dequeuesthe request and notifies the widget to redraw itself.
This single-thread model can yield poor performance unless your application is implemented properly. Specifically, if everything is happening in a single thread, performing long operations such as network access or databasequeries on the UI thread will block the whole user interface. No eventcan be