Android UI thread / main thread

UI thread 

When an application is launched, the system creates a thread called "main" for the application. The main thread, also called the UI thread, is very important because it is in charge of dispatching the events to the appropriate widgets, including drawing events. It is also the thread where your application interacts with running components of the Android UI toolkit.

Android UI principle: single-threaded model for the UI: the Android UI toolkit is not thread-safe and must always be manipulated on the UI thread.



在android中经常需要用到异步操作,Thread+Handler方式感觉繁琐,AsyncTask只能执行一次,很多需求不能满足,这时我们可以试试Activity提供的另外一种简单的方法runOnUiThread,runOnUiThread可以帮助你在线程中执行UI更新操作。

以下为代码:


  1. MyActivity.this. runOnUiThread(new Runnable() {   
  2.                     @Override   
  3.                         public void run() {   
  4.   
  5.                            // refresh ui 的操作代码  
  6.   
  7.                         }   
  8.                     });

  这里需要注意的是runOnUiThread是Activity中的方法,在线程中我们需要告诉系统是哪个activity调用,所以前面显示的指明了activity。

下面为runOnUiThread的代码
[java]  view plain copy
  1. public final void runOnUiThread(Runnable action) {  
  2.         if (Thread.currentThread() != mUiThread) {  
  3.             mHandler.post(action);  
  4.         } else {  
  5.             action.run();  
  6.         }  
  7.     }  

从代码可以看到,runOnUiThread首先判断是否是UI线程,不是的话就post,如果是的话就正常运行该线程.
只要经过主线程中的Handler.post或者postDelayed处理线程runnable则都可以将其转为UI主线程.再说Handler的机制就是来处理线程与UI通讯的.


原文链接:http://blog.csdn.net/androiddeveloper_lee/article/details/6790552

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值