子线程中进行UI操作

1. Handler的post()方法
  1. public class MainActivity extends Activity {  
  2.   
  3.     private Handler handler;  
  4.   
  5.     @Override  
  6.     protected void onCreate(Bundle savedInstanceState) {  
  7.         super.onCreate(savedInstanceState);  
  8.         setContentView(R.layout.activity_main);  
  9.         handler = new Handler();  
  10.         new Thread(new Runnable() {  
  11.             @Override  
  12.             public void run() {  
  13.                 handler.post(new Runnable() {  
  14.                     @Override  
  15.                     public void run() {  
  16.                         // 在这里进行UI操作  
  17.                     }  
  18.                 });  
  19.             }  
  20.         }).start();  
  21.     }  
  22. }  
2. View的post()方法
  1. public boolean post(Runnable action) {  
  2.     Handler handler;  
  3.     if (mAttachInfo != null) {  
  4.         handler = mAttachInfo.mHandler;  
  5.     } else {  
  6.         ViewRoot.getRunQueue().post(action);  
  7.         return true;  
  8.     }  
  9.     return handler.post(action);  
  10. }  
3. Activity的runOnUiThread()方法原理
  1. public final void runOnUiThread(Runnable action) {  
  2.     if (Thread.currentThread() != mUiThread) {  
  3.         mHandler.post(action);  
  4.     } else {  
  5.         action.run();  
  6.     }  
  7. }  
原理都是通过handler的post方法实现的
所有的post和sendMessage方法最后都会调用handler.sendMessage()方法进行入队操作,消息队列按照时间排序,之后使用Looper.loop方法出队, 每当有一个消息出队,就将它传递到msg.target的dispatchMessage()方法中,msg.target其实就是Handler,handleMessage方法:
  1. public void dispatchMessage(Message msg) {  
  2.     if (msg.callback != null) {  
  3.         handleCallback(msg);  
  4.     } else {  
  5.         if (mCallback != null) {  
  6.             if (mCallback.handleMessage(msg)) {  
  7.                 return;  
  8.             }  
  9.         }  
  10.         handleMessage(msg);  
  11.     }  
将消息对象作为参数传入handleMessage方法中
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值