我的实例:
package com.wyl.wylhandler; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class MainActivity extends ActionBarActivity { TextView tv; Button btn; Message msg; Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView)findViewById(R.id.textViewId); //获取TextView btn = (Button)findViewById(R.id.buttonId); //获取Button myOnclickListener l = new myOnclickListener();//实例化一个监听器l btn.setOnClickListener(l); //btn绑定上面获取的监听器l } class myOnclickListener implements OnClickListener{ @Override public void onClick(View v) { String c = "wyl";//设置断点用的 int len = c.length();//设置断点用的 System.out.println("len:"+len); //1 .通过handler对象来获取message myHandler myhandler = new myHandler(); msg = myhandler.obtainMessage(); String a = "zhang雅岚";//设置断点用的 msg.what = len; msg.obj = a; //handler sendMessage(msg)后,looper就自动从消息队列里取出msg(通过handleMessage方法), myhandler.sendMessage(msg); //handler把msg存入队列中 System.out.println("onClick所在线程:"+Thread.currentThread().getName()); } //调试发现,loop是在这一行的时候获取handler存入队列中的值msg } class myHandler extends Handler{ @Override public void handleMessage(Message message) { String name = "weiyongle"; //设置断点用的 int len2 = name.length(); //设置断点用的 System.out.println("len2:"+len2+","+"myHandler:"+Thread.currentThread().getName()); Object obj = message.obj; System.out.println("myHandler里打印出来:"+obj+"myHandler所在线程:"+Thread.currentThread().getName()); } } }