簡體   English   中英

Android上的view.post()和view.getHandler()。post()有什么區別?

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

有關view.post()文檔說:

使可運行對象添加到消息隊列。 可運行對象將在用戶界面線程上運行。

view.getHandler()返回以下內容:

運行 View的線程關聯的處理程序。

我了解可以在后台線程中創建視圖,但是它們將始終在UI線程上運行 這意味着view.getHandler()應該始終返回與UI線程關聯的處理程序-本質上是將view.getHandler()。post()和view.post()發布到同一MessageQueue中。

為什么要使用view.getHandler()。post()?

除了getHandler().post()可以將您扔到NullPointerException沒有什么區別,因為它可以返回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;
}

同時,這僅在相同條件下重定向,但返回布爾值。

/**
 * <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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM