您的位置:首页 > 产品设计 > UI/UE

Android Activity.runOnUiThread() 和 Handler

2016-03-23 10:49 531 查看
Android不允许在子线程中更新UI,所以最为常用的方法是用Handler,示例如下:

Handler myHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG:
//更新ui
break;
}
super.handleMessage(msg);
}
};


另外还有一种方法更为简便,就是使用 Activity 的 runOnUiThread() 方法,示例如下:

getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
//更新UI
}
});


我在使用的时候很困惑,不知道这两个有什么区别,最近我找到了答案,分享出来。

答案来自Stackoverflow:

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.

大致意思就是说Activity.runOnUiThread()是Handler的一个特定的实现,用Handler默认的构造器实例化的Handler并不代表”代码会运行在UI线程“,默认情况下,handler会绑定在被实例化的线程,所以为了保证我们的Handler中代码会运行在UI线程,我们需要用这种构造方式:

Handler mHandler = new Handler(Looper.getMainLooper());


下面再来看看runOnUiThread(),在android中它的源码如下:

/**
* Runs the specified action on the UI thread. If the current thread is the UI
* thread, then the action is executed immediately. If the current thread is
* not the UI thread, the action is posted to the event queue of the UI thread.
*
* @param action the action to run on the UI thread
*/
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}


我们看源码以及注释基本可以了解到如果不在UI线程运行runOnUiThread()方法,则会调用handler这种方式将事件放入UI线程更新队列,如果是在UI线程调用此方法,则会立即更新UI。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Android学习