一、View.post(Runnable )
源码
/**
* <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;
}
View.post(Runnable ) 是干啥的呢??官方说:
将Runnable添加到消息队列。runnable将在UI线程上运行。如果这会UI线程闲着,就直接帮你干活如果这会正忙,那就给你排个队等着吧
在细节点,就是在post(Runnable)方法里,View获得当前线程(即UI线程)的Handler,然后将action对象post到Handler里。 在Handler里,它将传递过来的action对象包装成一个Message(Message的callback为action),然后将其投入UI线程的消息循环中。 在Handler再次处理该Message时,有一条分支(未解释的那条)就是为它所设,直接调用runnable的run方法。而此时,在UI线程里,就可以来更新UI了。
示例:
new WebView(this).post(new Runnable() {
@Override
public void run() {
//你要在主线程做的事情
}
});
二、postDelayed (Runnable action, long delayMillis)
new WebView(this).postDelayed(new Runnable() {
@Override
public void run() {
//1秒后你要在主线程做的事情
}
},1000);
这哥们啥意思呢?就是可以让你延时1秒再做事情,其他和上面那货一毛一样啊,不信我们看看源码:
public boolean postDelayed(Runnable action, long delayMillis) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
return attachInfo.mHandler.postDelayed(action, delayMillis);
}
// Postpone the runnable until we know on which thread it needs to run.
// Assume that the runnable will be successfully placed after attach.
getRunQueue().postDelayed(action, delayMillis);
return true;
}
注意
由于不是在新的线程中使用,所以千万别做复杂的计算逻辑。