最简单的message与handler通信,学好这个是学习多线程通讯的基础,所以先从最简单的开始。
主代码:
package com.bvin.test.thread; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import android.widget.Button; public class MessageActivity extends Activity implements View.OnClickListener{ /** Called when the activity is first created. */ Button bt; Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); if(msg.what==0){ Log.e("哈哈", "接收到了消息哦"); } } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); initViews(); } void initViews(){ bt = (Button)findViewById(R.id.bt); bt.setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub if(v == bt){ //Message msg = new Message(); Message msg = Message.obtain(); msg.what = 0; handler.sendMessage(msg); } } }
1.点击开始按钮
用handler发送消息,log打出来
2.log栏查看: