Android Message里传送的数据[转]

package org.hualang.handlertest;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class HandlerTest4 extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.d("System.out","Activity所在线程的id:"+Thread.currentThread().getId());
        /**
         * 生成一个HandlerThread对象,实现了使用Looper来处理消息队列的功能
         * 这个类由Android应用程序框架提供
         */
        HandlerThread handlerThread = new HandlerThread("handlerThread");
        /**
         * 使用HandlerThread的getLooper()方法之前,必须先调用该类的start()方法,否则是个null,会报错
         */
        handlerThread.start();
        MyHandler handler = new MyHandler(handlerThread.getLooper());
        Message msg = handler.obtainMessage();
        /**
         * 将Message对象发送到目标对象
         * 所谓的目标对象,就是生成该msg对象的handler对象
         */
        //msg.obj = "Hello world";
        Bundle b = new Bundle();
        b.putInt("age", 22);
        b.putString("name", "loulijun");
        msg.setData(b);
        msg.sendToTarget();
    }
    class MyHandler extends Handler
    {
    public MyHandler()
    {
    }
    public MyHandler(Looper looper)
    {
    super(looper);
    }
    public void handleMessage(Message msg)
    {
    //String str = (String)msg.obj
    Bundle b = msg.getData();
    int age = b.getInt("age");
    String name = b.getString("name");
    Toast toast = Toast.makeText(getApplicationContext(), "age="+age+"name="+name, Toast.LENGTH_LONG);
    toast.show();
    Log.d("System.out", "handler所在线程的id:"+Thread.currentThread().getId());
    }
    }
}

如果是msg.obj,那么可以这样用

msg.obj = "Welcome to china";

然后在handleMessage()方法中用

String str = (String)msg.obj;来获得传递的值

 

如果使用getData()方法的话,需要用到Bundle对象来传递

 

来自:http://www.iteye.com/topic/1063216

posted @ 2013-07-12 10:55  M'  阅读(14989)  评论(0编辑  收藏  举报