自己闲暇之余随便写的demo(更新textView),布局里面只有一个按钮和TextView:
public class LooperHandlerActivity extends Activity {
//更新UI
private Handler mHandler;
private Button mBtn;
private TextView tv_UI;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_looper_handler);
tv_UI = (TextView) findViewById(R.id.tv_UI);
mBtn = (Button) findViewById(R.id.mBtn);
initThreadLooper();
}
private void initThreadLooper() {
mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
tv_UI.setText(msg.what+"");
if(msg.what == 9){
mBtn.setClickable(true);
}
}
};
mBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LooperThread thread = new LooperThread();
thread.setHandler(mHandler);
thread.start();
mBtn.setClickable(false);
}
});
}
/**
* 创建一个子线程
*/
class LooperThread extends Thread{
Handler handler;
public void setHandler(Handler handler){
this.handler = handler;
}
@Override
public void run() {
Looper.prepare();
for (int i = 0; i < 10; i++) {
try {
sleep(1000);
handler.sendEmptyMessageDelayed(i,0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Looper.loop();
}
}
}