Android 上的 view.post() 和 view.getHandler().post() 有什么区别?

What is the difference between view.post() and view.getHandler().post() on Android?

关于 view.post() 的文档说:

Causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread.

view.getHandler() return 如下:

A handler associated with the thread running the View.

我知道可以在后台线程中创建视图,但它们将始终在 UI 线程中 运行。这意味着 view.getHandler() 应该始终 return 与 UI 线程关联的处理程序 - 本质上使 view.getHandler().post() 和 view.post () posting 到同一个 MessageQueue。

我为什么要使用 view.getHandler().post() ?

除了 getHandler().post() 可以让您进入 NullPointerException 之外没有太大区别,因为它可以 return null。

/**
 * @return A handler associated with the thread running the View. This
 * handler can be used to pump events in the UI events queue.
 */
public Handler getHandler() {
    final AttachInfo attachInfo = mAttachInfo;
    if (attachInfo != null) {
        return attachInfo.mHandler;
    }
    return null;
}

同时,这只是在相同条件下重定向,但 return 是一个布尔值。

/**
 * <p>Causes the Runnable to be added to the message queue.
 * The runnable will be run on the user interface thread.</p>
 *
 * @param action The Runnable that will be executed.
 *
 * @return Returns true if the Runnable was successfully placed in to the
 *         message queue.  Returns false on failure, usually because the
 *         looper processing the message queue is exiting.
 *
 * @see #postDelayed
 * @see #removeCallbacks
 */
public boolean post(Runnable action) {
    final AttachInfo attachInfo = mAttachInfo;
    if (attachInfo != null) {
        return attachInfo.mHandler.post(action);
    }

    // Postpone the runnable until we know on which thread it needs to run.
    // Assume that the runnable will be successfully placed after attach.
    getRunQueue().post(action);
    return true;
}