Android编程之消息机制实例分析

2019-12-10 19:53:18王振洲

每一个线程里可含有一个Looper对象以及一个MessageQueue数据结构。在你的应用程序里,可以定义Handler的子类别来接收Looper所送出的消息。

同线程不同组件之间的消息传递:
 

  1. public class Activity1 extends Activity implements OnClickListener{    Button button = null; 
  2.   TextView text = null;    @Override 
  3.   protected void onCreate(Bundle savedInstanceState) {      super.onCreate(savedInstanceState); 
  4.     setContentView(R.layout.activity1);      button = (Button)findViewById(R.id.btn); 
  5.     button.setOnClickListener(this);      text = (TextView)findViewById(R.id.content); 
  6.   }    public void onClick(View v) { 
  7.     switch (v.getId()) {      case R.id.btn: 
  8.       Looper looper = Looper.myLooper();//取得当前线程里的looper        MyHandler mHandler = new MyHandler(looper);//构造一个handler使之可与looper通信 
  9.       //buton等组件可以由mHandler将消息传给looper后,再放入messageQueue中,同时mHandler也可以接受来自looper消息        mHandler.removeMessages(0); 
  10.       String msgStr = "主线程不同组件通信:消息来自button";        Message m = mHandler.obtainMessage(1, 1, 1, msgStr);//构造要传递的消息 
  11.       mHandler.sendMessage(m);//发送消息:系统会自动调用handleMessage方法来处理消息        break; 
  12.     }    } 
  13.   private class MyHandler extends Handler{      public MyHandler(Looper looper){ 
  14.       super(looper);      } 
  15.     @Override      public void handleMessage(Message msg) {//处理消息