一、流程
1.自定义Handler,重写handleMessage(Message msg),用msg得到bundle,从而得到传递过来的数据
2.开启android.os.HandlerThread,获取looper,据此为参数new一个自定义的Handler
3.以new出来的自定义的Handler得出Message,再得出bundle,从而写入要传给handler的数据,最后调用msg.sendToTarget();发送数据到msg队列,从而handler会自动调用handleMessage处理信息
二、代码
1.java
1 package mars.handler; 2 3 import android.app.Activity; 4 import android.os.Bundle; 5 import android.os.Handler; 6 import android.os.HandlerThread; 7 import android.os.Looper; 8 import android.os.Message; 9 10 public class HandlerTest2 extends Activity { 11 12 @Override 13 protected void onCreate(Bundle savedInstanceState) { 14 // TODO Auto-generated method stub 15 super.onCreate(savedInstanceState); 16 setContentView(R.layout.main); 17 //打印了当前线程的ID 18 System.out.println("Activity-->" + Thread.currentThread().getId()); 19 //生成一个HandlerThread对象,实现了使用Looper来处理消息队列的功能,这个类由Android应用程序框架提供 20 HandlerThread handlerThread = new HandlerThread("handler_thread"); 21 //在使用HandlerThread的getLooper()方法之前,必须先调用该类的start(); 22 handlerThread.start(); 23 //把handlerxdpg绑定到此looper的线程中 24 MyHandler myHandler = new MyHandler(handlerThread.getLooper()); 25 Message msg = myHandler.obtainMessage(); 26 //将msg发送到目标对象,所谓的目标对象,就是生成该msg对象的handler对象 27 Bundle b = new Bundle(); 28 b.putInt("age", 20); 29 b.putString("name", "Jhon"); 30 msg.setData(b); 31 msg.sendToTarget(); 32 } 33 34 class MyHandler extends Handler{ 35 public MyHandler(){ 36 37 } 38 public MyHandler(Looper looper){ 39 super(looper); 40 } 41 @Override 42 public void handleMessage(Message msg) { 43 Bundle b = msg.getData(); 44 int age = b.getInt("age"); 45 String name = b.getString("name"); 46 System.out.println("age is " + age + ", name is" + name); 47 System.out.println("Handler--->" + Thread.currentThread().getId()); 48 System.out.println("handlerMessage"); 49 } 50 } 51 }