Android中常用定时器
Timer
使用Timer可以每隔一段时间执行一次,与TimerTask一起使用。
Timer timer = new Timer();
TimerTask taskcc = new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
//每次执行的代码
}
}
});
};
// 参数分别是delay(多长时间后执行),duration(执行间隔)
timer.schedule(taskcc, 1000, 1000);//启动定时器
Handler
使用Handler的postDelayed方法可以实现定时,与Runnable一起使用。
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
//定时执行的代码
}
//参数分别是runnable(执行的runnable ) ,delay(多长时间后执行)
handler.postDelayed(runnable , 1000);
这样使用定时执行的代码只会执行一次,若要和timer 一样执行多次或一直执行只需在执行代码中再次启动即可。
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
//定时执行的代码
... ...
//定时执行的代码执行之后再次启动即可,此处可以重新设置执行多长时间后执行
handler.postDelayed(this, 1000);
}
//参数分别是runnable(执行的runnable ) ,delay(多长时间后执行)
handler.postDelayed(runnable , 1000);
Thread
public class MyThread implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
//执行的代码
Thread.sleep(10000);// 线程暂停10秒,单位毫秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// 在需要启动线程的地方加入下面语句:
new Thread(new MyThread()).start();