handler,主要接受子线程发送的数据, 并用此数据配合主线程更新UI。
//初始化定义几种消息,不同的消息刷新不同的UI
private final static int PROGRESS_CHANGED = 0;
private final static int PROGRESS_STOP = 1;
//定义handler,刷新UI
Handler myHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
switch(msg.what){
case PROGRESS_CHANGED:
//...
//收到PROGRESS_CHANGED时刷新UI
//每1000ms
sendEmptyMessageDelayed(PROGRESS_CHANGED, 1000);
break;
case PROGRESS_STOP
//...
//收到PROGRESS_STOP 时刷新UI
//每2000ms
sendEmptyMessageDelayedPROGRESS_STOP 2000);
break;
}
super.handleMessage(msg);
}
};
Handler运行在主线程中(UI线程中),它与子线程可以通过Message对象来传递数据:
(1)子线程发送消息
myHandler.sendEmptyMessage(PROGRESS_CHANGED);
(2)取消消息发送
myHandler.removeMessages(PROGRESS_CHANGED);