Ric*_*ich 91 android android-ui
任何人都可以告诉我,如果使用runOnUiThread()与Looper.getMainLooper().post()在Android中的UI线程上执行任务有什么区别吗?
关于我唯一可以确定的是,因为runOnUiThread是一个非静态的Activity方法,所以当你需要在一个看不到Activity的类中编写代码时,Looper.getMainLooper().post()会更方便(例如一个接口).
我不是在寻找关于是否应该在UI线程上执行某些事情的讨论,我知道有些事情不可能并且很多事情不应该,但是有些事情(比如启动AsyncTask)必须从UI线程.
谢谢,
R.
zap*_*apl 180
从后台线程调用时,以下行为相同:
运用 Looper.getMainLooper()
Runnable task = getTask();
new Handler(Looper.getMainLooper()).post(task);
Run Code Online (Sandbox Code Playgroud)运用 Activity#runOnUiThread()
Runnable task = getTask();
runOnUiThread(task);
Run Code Online (Sandbox Code Playgroud)唯一的区别是从那时起你从UI线程那样做
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
Run Code Online (Sandbox Code Playgroud)
将检查当前Thread是否已经是UI线程,然后直接执行它.将其作为消息发布将延迟执行,直到从当前UI线程方法返回.
还有第三种方法可以Runnable
在UI线程上执行View#post(Runnable)
- 即使从UI线程调用,它也会始终发布消息.这很有用,因为这样可以确保View
在执行代码之前已经正确构造并具有布局.