Difference between Handler.post(Runnable r) and Activity.runOnUiThread(Runnable r) [duplicate]

被刻印的时光 ゝ 提交于 2019-11-27 14:56:21

runOnUiThread is basically suited to show a progress dialog or do some UI manipulations before an AsyncTask call. If you want to update the UI in the middle of a thread execution, then the best approach is to create a Handler which will update your UI, and let the thread continue running, for example, updating a text view periodically after a few sec, say timer functionality.

From the official Handler docs

Handler

There are two main uses for a Handler:

(1) To schedule messages and runnables to be executed as some point in the future.

(2) To enqueue an action to be performed on a different thread than your own.

In short, Handler is used to manage different Runnables.

runOnUiThread

It is used to execute the non-UI operation on the UI Thread, example if you want to update the screen from AsyncTask's doInBackground() you have to write the part of code that update's the UI inside the runOnUiThread(). But again that will block the UI.

Guy

A Handler is attached to the thread it was created on.

handler.post(Runnable) can be used to run code on the thread Handler is attached to.

Activity.runOnUIThread(Runnable) always run the given runnable on the activity's UIThread. Internnaly it does so through a handler Activity creates when constructed like so:

final Handler mHandler = new Handler();

Hence runonUiThrad code looks like this:

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

As you can see if the current thread is not the UI thread, it posts the given runnable on its member handler which we referred to earlier. If the caller is already on the ui thread, it just calls the runnable.

Rad the code here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!