Android Message裡傳送的資料[轉]

M'發表於2013-07-12
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

相關文章