1.Handler
功能:主要是接收子线程的数据来更新主线程(UI).接收数据的主要方式是Message对象和Runnalbe对象
描述:Handler有两个作用, (1) : 定时执行Message和Runnalbe 对象
(2): 让一个动作,在不同的线程中执行.
class="code_img_closed" src="/Upload/Images/2014072815/0015B68B3C38AA5B.gif" alt="" />logs_code_hide('bcf2e610-c038-47cc-8714-c8b6435211d6',event)" src="/Upload/Images/2014072815/2B1B950FA3DF188F.gif" alt="" />1 public class MyHandlerActivity extends Activity { 2 Button button; 3 MyHandler myHandler; 4 5 protected void onCreate(Bundle savedInstanceState) { 6 super.onCreate(savedInstanceState); 7 setContentView(R.layout.handlertest); 8 9 button = (Button) findViewById(R.id.button); 10 myHandler = new MyHandler(); 11 // 当创建一个新的Handler实例时, 它会绑定到当前线程和消息的队列中,开始分发数据 12 // Handler有两个作用, (1) : 定时执行Message和Runnalbe 对象 13 // (2): 让一个动作,在不同的线程中执行. 14 15 // 它安排消息,用以下方法 16 // post(Runnable) 17 // postAtTime(Runnable,long) 18 // postDelayed(Runnable,long) 19 // sendEmptyMessage(int) 20 // sendMessage(Message); 21 // sendMessageAtTime(Message,long) 22 // sendMessageDelayed(Message,long) 23 24 // 以上方法以 post开头的允许你处理Runnable对象 25 //sendMessage()允许你处理Message对象(Message里可以包含数据,) 26 27 MyThread m = new MyThread(); 28 new Thread(m).start(); 29 } 30 31 /** 32 * 接受消息,处理消息 ,此Handler会与当前主线程一块运行 33 * */ 34 35 class MyHandler extends Handler { 36 public MyHandler() { 37 } 38 39 public MyHandler(Looper L) { 40 super(L); 41 } 42 43 // 子类必须重写此方法,接受数据 44 @Override 45 public void handleMessage(Message msg) { 46 // TODO Auto-generated method stub 47 Log.d("MyHandler", "handleMessage......"); 48 super.handleMessage(msg); 49 // 此处可以更新UI 50 Bundle b = msg.getData(); 51 String color = b.getString("color"); 52 MyHandlerActivity.this.button.append(color); 53 54 } 55 } 56 57 class MyThread implements Runnable { 58 public void run() { 59 60 try { 61 Thread.sleep(10000); 62 } catch (InterruptedException e) { 63 // TODO Auto-generated catch block 64 e.printStackTrace(); 65 } 66 67 Log.d("thread.......", "mThread........"); 68 Message msg = new Message(); 69 Bundle b = new Bundle();// 存放数据 70 b.putString("color", "我的"); 71 msg.setData(b); 72 73 MyHandlerActivity.this.myHandler.sendMessage(msg); // 向Handler发送消息,更新UI 74 75 } 76 } 77 78 }View Code