Looper.getMainLooper () //获得UI线程的Lopper
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
public class HandlerDemo extends Activity {
//title为setTitle方法提供变量,这里为了方便我设置成了int型
private int title = 0;
private Handler mHandler = new Handler(){
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
updateTitle();
break;
}
};
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new MyTask(), 1, 5000);
}
private class MyTask extends TimerTask{
@Override
public void run() {
Message message = new Message();
message.what = 1;
mHandler.sendMessage(message);
}
}
public void updateTitle(){
setTitle("Welcome to Mr Wei's blog " + title);
title ++;
}
}
public class Activity1 extends Activity implements OnClickListener{
Button button = null;
TextView text = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
button = (Button)findViewById(R.id.btn);
button.setOnClickListener(this);
text = (TextView)findViewById(R.id.content);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn:
Looper looper = Looper.myLooper();//取得当前 线程里的looper
MyHandler mHandler = new MyHandler(looper);//构造一个handler使之可与looper通信
//buton等 组件可以由mHandler将消息传给looper后,再放入messageQueue中,同时mHandler也可以接受来自looper消息
mHandler.removeMessages(0);
String msgStr = "主线程不同组件通信:消息来自button";
Message m = mHandler.obtainMessage(1, 1, 1, msgStr);//构造要传递的消息
mHandler.sendMessage(m);//发送消息:系统会自动调用handleMessage方法来处理消息
break;
}
}
private class MyHandler extends Handler{
public MyHandler(Looper looper){
super(looper);
}
@Override
public void handleMessage(Message msg) {//处理消息
text.setText(msg.obj.toString());
}
}
}