2017-04-25 70 views
0

文檔關於view.post()說:Android上的view.post()和view.getHandler()。post()有什麼區別?

原因被添加到消息隊列中的可運行。可運行的 將在用戶界面線程上運行。

view.getHandler()返回如下:與運行查看線程相關

的處理程序。

我明白了意見,可以在後臺線程創建,但他們將永遠在UI線程上運行。這意味着view.getHandler()應該總是返回一個與UI線程相關的處理程序 - 實質上是使view.getHandler()。post()和view.post()發佈到同一個MessageQueue。

爲什麼我應該使用view.getHandler()。post()?

+1

Android是開源... https://github.com/android/platform_frameworks_base/blob/master/core/java/android/view/View.java#L13928 –

回答

3

除了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; 
} 
相關問題