为什么要使用处理程序,同时runOnUiThread不一样吗? [英] Why to use Handlers while runOnUiThread does the same?

查看:259
本文介绍了为什么要使用处理程序,同时runOnUiThread不一样吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所遇到的两个处理程序和<一href="http://developer.android.com/reference/android/app/Activity.html#runOnUiThread%28java.lang.Runnable%29">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.

推荐答案

<一个href="http://developer.android.com/reference/android/app/Activity.html#runOnUiThread%28java.lang.Runnable%29">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.

这篇关于为什么要使用处理程序,同时runOnUiThread不一样吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆