2017-04-25 8 views
0

ドキュメントを約view.post()言う:Androidのview.post()とview.getHandler()。post()の違いは何ですか?

はRunnableを、メッセージ・キューに追加されるようにします。実行可能ファイル は、ユーザーインターフェイススレッドで実行されます。

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()は、nullを返すことができるので、NullPointerExceptionに投げることができます。

/** 
* @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; 
} 
関連する問題