runOnUiThread VS Looper.getMainLooper()。后在安卓 [英] runOnUiThread vs Looper.getMainLooper().post in Android

查看:244
本文介绍了runOnUiThread VS Looper.getMainLooper()。后在安卓的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我,如果有使用runOnUiThread()与Looper.getMainLooper()之间的区别。后()在Android的UI线程上执行任务??

Can anyone tell me if there's any difference between using runOnUiThread() versus Looper.getMainLooper().post() to execute a task on the UI thread in Android??

关于我唯一能确定的是,由于runOnUiThread是一种非静态的活动方式,Looper.getMainLooper()后()更方便,当你需要code的东西在一个类不能看到的活动(如接口)。

About the only thing I can determine is that since runOnUiThread is a non-static Activity method, Looper.getMainLooper().post() is more convenient when you need to code something in a class that can't see the Activity (such as an interface).

我不是在寻找是否有物体在UI线程上执行的讨论中,我得到了一些事情不能和一个伟大的很多事情不应该,但有些东西(如启动了一个AsyncTask的)都必须从UI线程中执行。

I'm not looking for a discussion on WHETHER something should be executed on the UI thread, I get that some things can't and a great many things shouldn't, however some things (like starting up an AsyncTask) MUST be executed from the UI thread.

谢谢,
R上。

Thanks,
R.

推荐答案

以下行为一样,从后台线程调用时

The following behaves the same when called from background threads

通过 Looper.getMainLooper()

    Runnable task = getTask();
    new Handler(Looper.getMainLooper()).post(task);

通过活动#runOnUiThread()

    Runnable task = getTask();
    runOnUiThread(task);

唯一的区别是,当你这样做,从UI线程,因为

The only difference is when you do that from the UI thread since

public final void runOnUiThread(Runnable action) {
    if (Thread.currentThread() != mUiThread) {
        mHandler.post(action);
    } else {
        action.run();
    }
}

会检查当前线程已经是UI线程,然后直接执行它。发布它作为一个消息将推迟执行,直到从当前UI线程方法返回。

will check if the current Thread is already the UI thread and then execute it directly. Posting it as a message will delay the execution until you return from the current UI-thread method.

还有到UI线程这将是<一上执行的Runnable 第三条道路href="http://developer.android.com/reference/android/view/View.html#post%28java.lang.Runnable%29"><$c$c>View#post(Runnable) - 这其中总会发布消息,即使从UI线程调用时。因为这将确保有用的是查看已正确构建具有code被执行前的布局。

There is also a third way to execute a Runnable on the UI thread which would be View#post(Runnable) - this one will always post the message even when called from the UI thread. That is useful since that will ensure that the View has been properly constructed and has a layout before the code is executed.

这篇关于runOnUiThread VS Looper.getMainLooper()。后在安卓的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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