runOnUiThread VS Looper.getMainLooper()。后在安卓VS、runOnUiThread、getMainLooper、Looper

2023-09-04 07:51:00 作者:百裹行者

谁能告诉我,如果有使用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线程这将是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.