ANDROID_MARS学习笔记_S01原始版_008_Looper\Bundle异步消息处理

一、代码
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 }

 

 

你可能感兴趣的:(ANDROID_MARS学习笔记_S01原始版_008_Looper\Bundle异步消息处理)