package net.csdn.leigo.handler.message; import net.csdn.leigo.handler.R; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.TextView; public class MainActivity extends Activity { private TextView mMsgTextView; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 3) { int arg1 = msg.arg1; int arg2 = msg.arg2; int what = msg.what; Object obj = msg.obj; Bundle bundle = msg.getData(); String data = bundle.getString("data"); mMsgTextView.setText("arg1:" + arg1 + ", arg2:" + arg2 + ", what:" + what + ", obj:" + obj.toString() + ", data:" + data); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMsgTextView = (TextView) findViewById(R.id.tv_msg); } public void sendMessage(View v) { new Thread(new Runnable() { @Override public void run() { // ----------------------------------第一种方式----------- // Message msg = Message.obtain(); // msg.arg1 = 100; // msg.arg2 = 200; // msg.what = 1; // msg.obj = " hello "; // handler.sendMessage(msg); // ----------------------------------------------------- // ----------------------------------第二种方式----------- // Message msg = Message.obtain(handler); // msg.arg1 = 100; // msg.arg2 = 200; // msg.what = 2; // msg.obj = " world "; // msg.sendToTarget(); // ----------------------------------------------------- // ----------------------------------第三种方式----------- //Message有很多重载方法,具体查看API,这里通过Bundle传递一个参数 Message msg = Message.obtain(handler, 3); Bundle bundle = new Bundle(); bundle.putString("data", "hello world"); msg.obj = " android "; msg.setData(bundle); msg.sendToTarget(); } }).start(); } }