标签:
代码如下:
1 package com.wyl.handler_mars; 2 3 import android.app.Activity; 4 import android.os.Bundle; 5 import android.os.Handler; 6 import android.os.Looper; 7 import android.os.Message; 8 import android.util.Log; 9 import android.view.View; 10 import android.view.View.OnClickListener; 11 import android.widget.Button; 12 import android.widget.TextView; 13 import android.widget.Toast; 14 /** 15 * 主线程发送消息,工作线程接收消息 16 * @author Wyl 17 * 18 */ 19 public class SecondActivity extends Activity implements OnClickListener{ 20 Button btn_fasong; 21 Handler hand; 22 Message msg; 23 TextView tv; 24 @Override 25 protected void onCreate(Bundle savedInstanceState) { 26 // TODO Auto-generated method stub 27 super.onCreate(savedInstanceState); 28 setContentView(R.layout.main2); 29 btn_fasong = (Button) findViewById(R.id.btn_send); 30 tv = (TextView) findViewById(R.id.tv_01); 31 btn_fasong.setOnClickListener(this); 32 Thread t = new MyThread(); 33 t.start(); 34 } 35 @Override 36 public void onClick(View v) { 37 //hand = new Handler();//这一行尤其重要,如果不注释掉,那么下面的线程中就没法接收到消息,因为这行代码中又重新生成了一个handler对象,也就对应着不同的looper,所以就没法 38 Message msg = hand.obtainMessage(); 39 msg.obj = "无语了。。。"; 40 System.out.println("onClick()...发送:"+"无语了。。。"); 41 hand.sendMessage(msg);//主线程发送消息 42 } 43 44 45 class MyThread extends Thread{ 46 47 @Override 48 public void run() { 49 Looper.prepare();//获取一个Looper对象 50 System.out.println("==========="); 51 hand = new Handler(){ 52 53 @Override 54 public void handleMessage(Message msg) { 55 // TODO Auto-generated method stub 56 System.out.println("MyThread.run()接收到了消息"+",所在线程:"+Thread.currentThread().getName()); 57 } 58 }; 59 Looper.loop(); 60 } 61 62 } 63 }
标签:
原文地址:http://www.cnblogs.com/Sunnor/p/4859868.html