在主线程中可以直接创建Handler对象,而在子线程中需要先调用Looper.prepare()才能创建Handler对象。
1.在线程中使用handler,更新ui线程
//handler为全局变量
Handler handler=new Handler();
new Thread(){
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
handler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
在此写ui线程更新方法
text.setText(String.valueOf(i));
}
});
}
};
2.在线程中调用sendEmptyMessage(),然后再handler中更新ui线程
Handler handler=new Handler(){
public void handleMessage(Message msg) {
if (msg.what==1) {
text.setText(String.valueOf(msg.arg1));
}
};
};
new Thread(){
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
handler.sendEmptyMessage(1);
}
};
3.使用runOnUiThread(new Runnable)
public void handler3(){
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
text.setText(String.valueOf(i));
}
});
}
new Thread(){
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
handler3();
}
};
4.使用控件的post(new Runnable)
public void handler4(){
text.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
text.setText(String.valueOf(i));
}
});
}
new Thread(){
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
handler4();
}
};