什么是 Android UiThread (UI 线程)

谁能给我解释一下 UI 线程到底是什么? Developer.android.com 上写着 runonuiThread 函数

Public final void runOnUiThread (Runnable action)

在 UI 线程上运行指定的操作 当前线程是 UI 线程,然后执行操作 如果当前线程不是 UI 线程,则操作为 发送到 UI 线程的事件队列。

UI 线程是否意味着每次活动被某些 UI 活动(如传入呼叫或屏幕变暗等)推到后台时,这个线程都会运行?如果没有,UI 线程到底包括什么?

谢谢你

87729 次浏览

All UI drawings etc. happen in a separate thread. Its called the UIThread. If you want to make any change to UI u must use make sure it happens in UIThread's context. Easiest way of doing it is to make use of runOnUiThread

The UIThread is the main thread of execution for your application. This is where most of your application code is run. All of your application components (Activities, Services, ContentProviders, BroadcastReceivers) are created in this thread, and any system calls to those components are performed in this thread.

For instance, let's say your application is a single Activity class. Then all of the lifecycle methods and most of your event handling code is run in this UIThread. These are methods like onCreate, onPause, onDestroy, onClick, etc. Additionally, this is where all of the updates to the UI are made. Anything that causes the UI to be updated or changed HAS to happen on the UI thread.

For more info on your application's Processes and Threads click here.

When you explicitly spawn a new thread to do work in the background, this code is not run on the UIThread. So what happens if this background thread needs to do something that changes the UI? This is what the runOnUiThread is for. Actually you're supposed to use a Handler (see the link below for more info on this). It provides these background threads the ability to execute code that can modify the UI. They do this by putting the UI-modifying code in a Runnable object and passing it to the runOnUiThread method.

For more info on spawning worker threads and updating the UI from them click here

I personally only use the runOnUiThread method in my Instrumentation Tests. Since the test code does not execute in the UIThread, you need to use this method to run code that modifies the UI. So, I use it to inject click and key events into my application. I can then check the state of the application to make sure the correct things happened.

For more info on testing and running code on the UIThread click here

If you execute blocking code (e.g. a Http-Request) in a separate Thread, consider using AsyncTask. Its doInBackground-Method runs on a separate Thread. AsyncTask provides you with methods onProgressUpdate and onPostExecute which are guaranteed to run on the UI thread.

If you need GUI-progress updates (e.g. via a progressbar) call publishProgress inside doInBackground. This leads to a subsequent call of onPublishProgress which is also guaranteed to run on the UI thread.

onPostExecute is automatically called after doInBackground returns.