在 Android 中的 runOnUiThread vs Looper.getMainLooper() . post

有人能告诉我在 Android 的 UI 线程上使用 runOnUiThread()和使用 Looper.getMainLooper().post()执行任务有什么区别吗?

The only thing I can determine is that since runOnUiThread is a non-static Activity method, Looper.getMainLooper().post() is more convenient when you need to code something in a class that can't see the Activity (such as an interface).

我不是在讨论是否应该在 UI 线程上执行某些东西,我知道有些东西不能,很多东西不应该,但是,有些东西(如启动一个 AsyncTask)必须从 UI 线程上执行。

53324 次浏览

The following behaves the same when called from background threads:

  • 使用 Looper.getMainLooper()

    Runnable task = getTask();
    new Handler(Looper.getMainLooper()).post(task);
    
  • using Activity#runOnUiThread()

    Runnable task = getTask();
    runOnUiThread(task);
    

The only difference is when you do that from the UI thread since

public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}

将检查当前线程是否已经是 UI 线程,然后直接执行它。将其作为消息发布将延迟执行,直到从当前 UI 线程方法返回。

There is also a third way to execute a Runnable on the UI thread which would be View#post(Runnable) - this one will always post the message even when called from the UI thread. That is useful since that will ensure that the View has been properly constructed and has a layout before the code is executed.