标签:
往下看之前,需要了解一下Java的ThreadLocal类,可参考博文:
我们分析一下之前的这段代码,查看一下Handler机制中,Handle、Looper和MessageQueue之间到底是什么关系
package cn.lixyz.handlertest; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { private Button button; private Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Message msg = handler.obtainMessage(); msg.what = 100; handler.sendMessage(msg); Log.d("TTTT", "sendMessage:" + Thread.currentThread().getName()); } }); WorkerThread wt = new WorkerThread(); wt.start(); } class WorkerThread extends Thread { @Override public void run() { super.run(); Looper.prepare(); handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); Log.d("TTTT", "handleMessage:" + Thread.currentThread().getName()); int i = msg.what; Log.d("TTTT", "收到了消息对象:" + i); } }; Looper.loop(); } } }
Android笔记(三十三) Android中线程之间的通信(五)Thread、Handle、Looper和MessageQueue
标签:
原文地址:http://www.cnblogs.com/xs104/p/4820398.html