Android异步线程与Bundle消息传递

yeaperyeo 2011-03-14

package com.lzr;
/////验证异步线程
/////先修改AndroidManifest.xml来默认启动HanderTest2这个Activity
////使用Looper来启动另一个线程实现handler
////HandlerThread对象用法
////Bundle对象用法
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 Handlertest2 extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		//打印当前线程的ID
		System.out.println("Activity--->"+Thread.currentThread().getId());
		
		///生成一个HandlerThread线程对象,实现使用Looper来处理消息队列的功能,这个类由Android提供
		HandlerThread handlerThread=new HandlerThread("handler_thread");
	////在使用HandlerThread的getLooper()方法前,必须先调用start()启动线程
		handlerThread.start();  
		
	  ////
		MyHandler myHandler=new MyHandler(handlerThread.getLooper());
		Message msg=myHandler.obtainMessage();
		
	  ////生成Bundle对象
		Bundle b=new Bundle();
		b.putInt("age", 25);
		b.putString("name", "make");
		msg.setData(b);
	////将msg发送到目标对象,所谓目标对象,就是生成该对象的handler对象,如myHandler
		msg.sendToTarget();///调用当生成的对象发送给handleMessage(Message msg)
		
		
	
	}
	   class MyHandler extends Handler{
         
		   	public MyHandler()
		   	{}
		   	////使用looper来使Handler从另外一个线程中的消息队列中取得数据
		   	public MyHandler(Looper looper)
		   	{
		   		super(looper);
		   	}
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			///super.handleMessage(msg);
			Bundle b=msg.getData();
			int age=b.getInt("age");
			String name=b.getString("name");
			System.out.println("age is"+age+" name is"+name);
			System.out.println("handler--->"+Thread.currentThread().getId());
			System.out.println("handlerMessage");
			
		}
	    	  
	      }
   
	
}

相关推荐