Android 更新UI的两种方法——handler和runOnUiThread()

Posted H_bolin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android 更新UI的两种方法——handler和runOnUiThread()相关的知识,希望对你有一定的参考价值。

今天看到了一个runOnUiThread()方法用来更新UI,觉得很神奇!!

方法一:handler机制不说了。

方法二:利用Activity.runOnUiThread(Runnable)把更新ui的代码创建在Runnable中,然后在需要更新ui时,把这个Runnable对象传给Activity.runOnUiThread(Runnable)。 这样Runnable对像就能在ui程序中被调用。如果当前线程是UI线程,那么行动是立即执行。如果当前线程不是UI线程,操作是发布到事件队列的UI线程
 
FusionField.currentActivity.runOnUiThread(new Runnable()    
        {    
            public void run()    
            {    
                Toast.makeText(getApplicationContext(), , "Update My UI",    
                        Toast.LENGTH_LONG).show();    
            }    
    
        });  

public final void runOnUiThread (Runnable action)

Added in API level 1

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.

如果当前线程是UI主线程,则直接执行Runnable的代码;否则将Runnable post到UI线程的消息队列。  --看代码实现就知道了

Parameters

action   the action to run on the UI thread

public final void runOnUiThread(Runnable action) {  
       if (Thread.currentThread() != mUiThread) {  
           mHandler.post(action);//将Runnable Post到消息队列,由内部的mHandler来处理,实际上也是Handler的处理方式  
       } else {  
           action.run();//已经在UI线程,直接运行。  
       }  
   }  

 

参考地址:

http://www.android100.org/html/201406/07/20384.html

http://blog.csdn.net/annkie/article/details/8496219

 

 

以上是关于Android 更新UI的两种方法——handler和runOnUiThread()的主要内容,如果未能解决你的问题,请参考以下文章

Android中的Handle(句柄)

在多线程中,子线程更新主线程ui都有哪些方法及注意点

Android_AyscnTask

关于Android

Android中实现全屏无标题栏的两种办法

[转]MFC子线程中更新控件内容的两种办法