(1)进程间通信交换信息的一种方式--使用handler;
(2)在主线程中new一个Handler对象,并重写他的handlerMessage(Message msg)方法;
(3)Message中有几个属性,可以用来传递简单的int型的参数(一般定义多个static final int 的常量)用来给What分类;
(4)obj属性可以用来传递其他对象,其中arg1和arg2两个属性可以用来储存int消息内容。
下面是一个activity_main布局
下面是主要Activity代码
public class MainActivity extends Activity {
private final static String TAG = "THREAD_ACTIVITY"; //调试标记
public final static int MUTI_THREAD = 0;//用于what属性的标记变量
public final static int COMPLETE_THREAD = 1;//用于what属性的标记变量
private Button btn; private TextView tv;
private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) //重写处理消息的方法
{ if(msg.what==MUTI_THREAD)
{ tv.setText(""+msg.arg1); }
else if(msg.what==COMPLETE_THREAD)
{ tv.setText("complete"); btn.setText("complete"); }
super.handleMessage(msg); } };
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener( new OnClickListener() {
@Override public void onClick(View v) {
start_thread(); btn.setText("running...");
}
});
}
private void start_thread() {
// TODO Auto-generated method stub
new Thread(){ //新线程
@Override public void run() {
// TODO Auto-generated method stub
int i = 100;
int j = 0;
Message msg = new Message();
for(j=1;j<i;j++){
Log.v(TAG, "J = "+j);
msg.what = MUTI_THREAD;
msg.arg1 = j;
handler.sendMessage(msg); //每次发送一个消息
try {
Thread.sleep(1000); }
catch (InterruptedException e) {
// TODO Auto-generated catch block e.printStackTrace(); }
}
msg.what = COMPLETE_THREAD;
handler.sendMessage(msg); //完成时修改what属性 }
}.start();
}
}
注意:在运行前必须加入permission权限INTERNET