我所遇到的两个处理程序和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
发
它在后台执行的web服务,现在我想更新UI。
For example consider a Runnable
Thread
which performs a web service in the background and now I want to update the UI.
什么是更新我的UI的最佳方法是什么?我应该去处理程序
或 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()是更通用处理程序的一个特例。随着处理程序
您可以创建自己的线程在自己的事件查询。使用处理程序
实例化默认构造 不的意思是的 code将运行UI线程的一般。默认情况下,处理程序绑定到发
从他们是从实例化。
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 default constructor doesn't mean "code will run on UI thread" in general. By default, handlers binded to Thread
from which they was instantiated from.
要创建处理程序
这是保证绑定到UI(主)线程,你应该创建处理程序
对象绑定到主尺蠖的是这样的:
To create Handler
that is guaranteed to bind to UI (main) thread you should create Handler
object binded to Main Looper like this:
Handler mHandler = new Handler(Looper.getMainLooper());
此外,如果您检查 runOnuiThread()
方法的实现,它使用处理程序
做的事情
Moreover, if you check the implementation of 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();
}
}
正如你可以从上面code片段中看到,的Runnable行动
将被立即执行,如果 runOnUiThread()
从UI线程调用。否则,将其发布到处理程序
,它会在某个点后执行。
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.