Handler 是一個消息分發對象。handler是Android給咱們提供用來更新UI的一套機制,也是一套消息處理機制,經過它能夠實如今不一樣線程之間傳遞消息java
本章Handler類要用到的方法有:android
void handleMessage(Message msg); //須要重寫的方法,用來處理接收的消息,只有當接收到發送者發來的消息,纔會回調該方法 Message obtainMessage(); //獲取一個消息對象 boolean sendMessage(Message msg); //發送消息對象,發送成功的話,就會回調handleMessage()方法
2.MainActivity.java以下所示:app
package com.example.tcpdemo; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Activity; import android.view.Menu; public class MainActivity extends Activity { MyThread mt; //定義一個handler public Handler mHandler = new Handler() { public void handleMessage(Message msg) { //打印發送者發來的消息 System.out.println("main what:"+msg.what); System.out.println("main obj:"+msg.obj.toString()); System.out.println("main arg1:"+msg.arg1); }; }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mt = new MyThread(); mt.setHandler(mHandler); //設置handler mt.start(); //啓動線程 } }
3.MyThread.java以下所示:tcp
package com.example.tcpdemo; import android.os.Handler; import android.os.Message; public class MyThread extends Thread { public Handler mHandler=null; //獲取另外一個線程的Handler public void setHandler( Handler handler){ mHandler = handler; } public void run(){ try { //讓線程睡眠3s。 Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } Message msg = mHandler.obtainMessage(); //設置發送的內容 msg.arg1 = 1; msg.what = 3; msg.obj = "this is MyThread"; mHandler.sendMessage(msg); } }
運行打印:ide