Android Activity.runOnUiThread() 和 Handler
2016-03-23 10:49
531 查看
Android不允许在子线程中更新UI,所以最为常用的方法是用Handler,示例如下:
另外还有一种方法更为简便,就是使用 Activity 的 runOnUiThread() 方法,示例如下:
我在使用的时候很困惑,不知道这两个有什么区别,最近我找到了答案,分享出来。
答案来自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线程,我们需要用这种构造方式:
下面再来看看runOnUiThread(),在android中它的源码如下:
我们看源码以及注释基本可以了解到如果不在UI线程运行runOnUiThread()方法,则会调用handler这种方式将事件放入UI线程更新队列,如果是在UI线程调用此方法,则会立即更新UI。
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进阶
- android开发学习如何一体化?从入门到高端开发的路如何走?
- Android学习
- Android学习资料
- Android开发学习路线图
- 安卓广播学习整理
- 安卓基于位置的服务学习整理
- 黑马程序员JAVA笔记1--java基础和概述
- Android学习笔记之Activity
- android学习二:适配器Adapter的使用
- 黑马程序员--类型转换问题
- Android 数据传递方式
- Android官方教程中文版
- Android 界面心得
- 自己写的一个Android小程序
- setOnClickListener()与报错OnClickListener()原因
- Android开发之adb命令
- 安卓学习笔记(LinearLayout属性android:orientation)