最新消息:热烈庆祝IT小记上线!

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 plaincopy
  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

猜您喜欢

备案号:苏ICP备12016861号-4