runOnUiThread vs Looper.getMainLooper().post in Android

前端 未结 1 1353
失恋的感觉
失恋的感觉 2020-11-29 15:53

Can anyone tell me if there\'s any difference between using runOnUiThread() versus Looper.getMainLooper().post() to execute a task on the UI thread in Android??

Abou

相关标签:
1条回答
  • 2020-11-29 16:13

    The following behaves the same when called from background threads:

    • using 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();
        }
    }
    

    will check if the current Thread is already the UI thread and then execute it directly. Posting it as a message will delay the execution until you return from the current UI-thread method.

    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.

    0 讨论(0)
提交回复
热议问题