1.为什么要用Handler
解决子线程不能刷新UI和主线程不能进行耗时操作的问题
2.什么是Handler
处理者,负责Message的发送及处理。使用Handler时,需要实现handleMessage(Message msg)方法来对特定的Message进行处理,例如更新UI等
3.什么是Looper
消息泵,不断地从MessageQueue中抽取Message执行。因此,一个MessageQueue需要一个Looper,针对接收Message消息线程
4.什么是MessageQueue
消息队列,用来存放Handler发送过来的消息,并按照FIFO规则执行。当然,存放Message并非实际意义的保存,而是将Message以链表的方式串联起来的,等待Looper的抽取
5.Handler怎么用
package com.wxl.looper;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity {
private TextView textView;
private Button button;
private MyThread thread;
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)this.findViewById(R.id.textView);
button = (Button)this.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Message message = Message.obtain();
message.what = 1;
message.obj = "hello world";
handler.sendMessage(message);
}
});
thread = new MyThread();
}
public class MyThread extends Thread
{
public MyThread() {
// TODO Auto-generated constructor stub
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if (1 == msg.what)
{
textView.setText(""+msg.obj);
}
}
};
}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
}
}
}
6.案例解析–倒计时Demo
package com.android.tutor;
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 {
private int title = 10;
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(title+"..... ");
title --;
}
}