Reputation: 11309
Documentation about view.post()
says:
Causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread.
view.getHandler()
returns the following:
A handler associated with the thread running the View.
I understand views can be created in a background thread, but they will always run on the UI thread. Which implies view.getHandler() should always return a handler associated with UI thread - essentially making view.getHandler().post() and view.post() posting to the same MessageQueue.
Why should I ever use view.getHandler().post() ?
Upvotes: 0
Views: 1460
Reputation: 191738
There isn't much difference other than getHandler().post()
can throw you to a NullPointerException
since it can 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;
}
Meanwhile, this simply redirects under the same conditions, but returns a boolean.
/**
* <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;
}
Upvotes: 3