Androids Handler.post,究竟会发生什么 [英] Androids Handler.post, what happens exactly
问题描述
几天以来,我试图弄清楚如果我在
since several days, I tried to figure out what exactly happens if I execute code in
void function(){
//somePreExecutionCode
new Handler().post(new Runnable(){
@Override
public void run(){
//someCode
}
});
}
似乎并没有阻塞UI,因此,在someCode完成之前,调用function()的按钮不会停留在单击位置. 但是,如果somePreExecutionCode启动progressBar,则someCode完成后的同一时刻将显示progressBar. 我知道,有AsyncTasks用于,但是还有其他可能性吗?
It seems like it isn't blocking the UI, so buttons, which calls function() doesn't stuck in the clicked position until someCode has finished. But if somePreExecutionCode starts a progressBar, the progressBar is shown at exactly the same moment, when someCode has finished. I know, there are AsyncTasks for, but is there any other possibility?
和
new Handler().post
和
View.post
?
推荐答案
简单地说,有 Looper线程,例如 UI线程.这样的线程具有自己的 Looper ,该线程为该线程运行消息循环.
Putting it simply, there are Looper threads, for example, UI thread. Such thread has its own Looper, which runs a message loop for the thread.
此类线程通常具有 Handler ,该线程对其进行处理Looper
的消息-覆盖public void handleMessage(Message msg)
或执行Runnable
,该消息已发布到其循环程序的消息队列中.
Such thread, typically, has a Handler, which processes its Looper
's messages - overriding public void handleMessage(Message msg)
or executing a Runnable
, which was posted to it's looper's message queue.
当您在 UI线程的上下文中创建Handler
时(就像您在代码中所做的那样),它与 UI线程的循环程序相关联,因此您的\\someCode
在 UI线程上运行.
When you're creating a Handler
in the context of UI thread (like you did in your code), it gets associated with UI thread's looper, so your \\someCode
runs on UI thread.
我想,在您的用例中,new Handler().post(Runnable)
和View:post(Runnable)
几乎是相同的,因为它们都在 UI线程消息队列中添加了Runnable
.
I guess, in your use case new Handler().post(Runnable)
and View:post(Runnable)
are mostly the same, as they both add a Runnable
to the UI thread message queue.
但是它们并不相同.
-
View:post(Runnable)
将在 UI线程循环程序的消息队列中添加Runnable
; -
Handler:post(Runnable)
会将Runnable
添加到其关联的线程循环程序的消息队列
View:post(Runnable)
will add aRunnable
to the UI thread looper's message queue;Handler:post(Runnable)
will add aRunnable
to its associated thread looper's message queue
我的解释非常直观,所以如果我错了,请纠正我.
My explanation is pretty much intuitive, so correct me anyone if I am wrong.
这篇关于Androids Handler.post,究竟会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!