每一个线程里可含有一个Looper对象以及一个MessageQueue数据结构。在你的应用程序里,可以定义Handler的子类别来接收Looper所送出的消息。
同线程不同组件之间的消息传递:
- public class Activity1 extends Activity implements OnClickListener{ Button button = null;
- TextView text = null; @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:
- Looper looper = Looper.myLooper();//取得当前线程里的looper MyHandler mHandler = new MyHandler(looper);//构造一个handler使之可与looper通信
- //buton等组件可以由mHandler将消息传给looper后,再放入messageQueue中,同时mHandler也可以接受来自looper消息 mHandler.removeMessages(0);
- String msgStr = "主线程不同组件通信:消息来自button"; Message m = mHandler.obtainMessage(1, 1, 1, msgStr);//构造要传递的消息
- mHandler.sendMessage(m);//发送消息:系统会自动调用handleMessage方法来处理消息 break;
- } }
- private class MyHandler extends Handler{ public MyHandler(Looper looper){
- super(looper); }
- @Override public void handleMessage(Message msg) {//处理消息










