HandlerThread分线程启动handler
import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; public class MainActivity extends Activity{ /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 打印UI线程的名称 System.out.println("onCreate CurrentThread = " + Thread.currentThread().getName()); setContentView(R.layout.activity_main); // 实现了使用Looper来处理消息队列的功能 HandlerThread handler = new HandlerThread("handler_Thread"); handler.start(); MyHandler myHandler = new MyHandler(handler.getLooper()); Message msg = myHandler.obtainMessage(); msg.obj = "abc"; Bundle data = new Bundle(); data.putString("title", "你好吗"); data.putString("info", "哈哈哈哈"); msg.setData(data); // 将msg发送到对象,所谓的目标对象就是生成该msg对象的Handler对象 msg.sendToTarget(); } class MyHandler extends Handler { public MyHandler() { } public MyHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub String s = (String) msg.obj; Bundle data = msg.getData(); String title=data.getString("title"); String info=data.getString("info"); System.out.println("title is " + title + ", info is" + info); System.out.println("msg.obj is " + s); System.out.println(Thread.currentThread().getId()); System.out.println("handlerMessage"); } } }
HandlerThread继承与Thread,所以本身就是一个线程。他类似于创建了一个含有Looper对象的线程类,而Looper可以用于创建Handler类,这样我们就不用自己实例化Looper对象,调用preare和Loop了,而是直接调用HandlerThread。与普通的Thread相比,就是多了Looper对象。