Android高手进阶教程 Android Handler的使用
2010-05-08 18:13:00 来源:WEB开发网大家好我们这一节讲的是Android Handler的使用,在讲Handler之前,我们先提个小问题,就是如何让程序5秒钟更新一下Title.
首先我们看一下习惯了Java编程的人,在不知道Handler的用法之前是怎么样写的程序,代码如下所示:
view plaincopy to clipboardprint?
package com.android.tutor;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
public class HandlerDemo extends Activity {
//title为setTitle方法提供变量,这里为了方便我设置成了int型
private int title = 0;
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() {
setTitle("Welcome to Mr Wei's blog " + title);
title ++;
}
}
}
package com.android.tutor;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
public class HandlerDemo extends Activity {
//title为setTitle方法提供变量,这里为了方便我设置成了int型
private int title = 0;
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() {
setTitle("Welcome to Mr Wei's blog " + title);
title ++;
}
}
}
然而当我们执行程序,并不能达到我们预期的效果,所以Android 引进了Handler
更多精彩
赞助商链接