Android消息处理机制(二)

角色综述(回顾): (1)UI thread 通常就是main thread,而Android启动程序时会替它建立一个MessageQueue

(2)当然需要一个Looper对象,来管理该MessageQueue

(3)我们可以构造Handler对象来push新消息到Message Queue里;或者接收Looper(Message Queue取出)所送来的消息。

(4)线程AHandler对象可以传递给别的线程,让别的线程BC等能送讯息来给线程A(存于AMessage Queue)

(5)线程AMessage Queue里的消息,只有线程A所属的对象可以处理。

 

子线程传递消息给主线程

public class Activity2 extends Activity implements OnClickListener{

       Button button = null;

       TextView text = null;

       MyHandler mHandler = null;

       Thread thread ;

       @Override

       protected void onCreate(Bundle savedInstanceState) {

              super.onCreate(savedInstanceState);

              setContentView(R.layout.activity1);        

              button = (Button)findViewById(R.id.btn);

              button.setOnClickListener(this);

              text = (TextView)findViewById(R.id.content);

       }

       public void onClick(View v) {

              switch (v.getId()) {

              case R.id.btn:

                     thread = new MyThread();

                     thread.start();

                     break;

              }            

       }     

       private class MyHandler extends Handler{             

              public MyHandler(Looper looper){

                     super(looper);

              }

              @Override

              public void handleMessage(Message msg) {//处理消息

                     text.setText(msg.obj.toString());

              }            

       }

       private class MyThread extends Thread{

              @Override

              public void run() {

                     Looper curLooper = Looper.myLooper();

                     Looper mainLooper = Looper.getMainLooper();

                     String msg ;

                     if(curLooper==null){

                            mHandler = new MyHandler(mainLooper);

                            msg = "curLooper is null";

                     }else{

                            mHandler = new MyHandler(curLooper);

                            msg = "This is curLooper";

                     }

                     mHandler.removeMessages(0);

                     Message m = mHandler.obtainMessage(1, 1, 1, msg);

                     mHandler.sendMessage(m);

              }            

       }

}

说明:

Android会自动替主线程建立Message Queue。在这个子线程里并没有建立Message Queue。所以,myLooper值为null,而mainLooper则指向主线程里的Looper。于是,执行到:

mHandler = new MyHandler (mainLooper);

mHandler属于主线程。

   mHandler.sendMessage(m);

就将m消息存入到主线程的Message Queue里。mainLooper看到Message Queue里有讯息,就会作出处理,于是由主线程执行到mHandlerhandleMessage()来处理消息。

下一节将会写一个关于应多线程请求网络数据的例子。

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值