为什么在 runOnUiThread 做同样的事情时使用处理程序? [英] Why to use Handlers while runOnUiThread does the same?
问题描述
我遇到过处理程序和runOnUiThread 概念.但对我来说,它们究竟在哪些事实上存在差异似乎仍然存在疑问.
I have come across both Handlers and runOnUiThread concepts. But to me it still seems to be a doubt as on which facts do they differ exactly.
它们都旨在从后台线程执行 UI 操作.但是,我们在这两种方法中进行选择时需要考虑哪些因素.
They both are intended to do UI actions from a background thread. But what are the factors that are to be considered while we choose among the two methods.
例如,考虑一个 Runnable
Thread
在后台执行 Web 服务,现在我想更新 UI.
For example consider a Runnable
Thread
which performs a web service in the background and now I want to update the UI.
更新用户界面的最佳方式是什么?我应该选择 Handler
还是 runOnUiThread
?
What would be the best way to update my UI? Should I go for Handler
or runOnUiThread
?
我仍然知道我可以使用 AsyncTask
并利用 onPostExecute
.但我只想知道区别.
I still know I could use a AsyncTask
and make use of onPostExecute
. But I just want to know the difference.
推荐答案
Activity.runOnUiThread() 是更通用的 处理程序.使用 Handler
,您可以在自己的线程中创建自己的事件查询.使用 Handlers
实例化的 default构造函数 并不一般意味着代码将在 UI 线程上运行".默认情况下,处理程序绑定到从中实例化它们的 Thread
.
Activity.runOnUiThread() is a special case of more generic Handlers. With Handler
you can create your own event query within your own thread. Using Handlers
instantiated with the default constructor doesn't mean "code will run on UI thread" in general. By default, handlers are bound to the Thread
from which they were instantiated from.
要创建一个保证绑定到 UI(主)线程的 Handler
,你应该创建一个绑定到 Main LooperHandler 对象> 像这样:
To create a Handler
that is guaranteed to bind to the UI (main) thread, you should create a Handler
object bound to Main Looper like this:
Handler mHandler = new Handler(Looper.getMainLooper());
此外,如果你检查runOnUiThread()
方法的实现,它正在使用Handler
来做事情:
Moreover, if you check the implementation of the runOnUiThread()
method, it is using Handler
to do the things:
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
从上面的代码片段可以看出,如果从 UI 线程调用 runOnUiThread()
,Runnable action
将立即执行.否则,它会将其发布到 Handler
,后者将在稍后的某个时刻执行.
As you can see from code snippet above, Runnable action
will be executed immediately if runOnUiThread()
is called from the UI thread. Otherwise, it will post it to the Handler
, which will be executed at some point later.
这篇关于为什么在 runOnUiThread 做同样的事情时使用处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!