1、CountDownTimer 在Android中實作了倒計時的功能,
CountDownTimer(long millisInFuture, long countDownInterval)
在初始化時有兩個輸入參數:
millisInFuture:倒計時的總時間,30000 即為30秒
countDownInterval:為在倒計時過程中調用 onTick()方法的時間間隔,如1000,即為每隔1秒觸發一次onTick()方法;為2000,則每隔2秒觸發一次。
因而可以在 onTick() 方法中進行倒計時時間顯示等操作
當倒計時結束時便會調用 onFinsh()方法。
還要注意 需要使用 start()方法進行倒計時啟動
另外,調用 cancel()方法 可以取消倒計時操作。
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
2、另外也可以通過Timer來實作倒計時操作:
Timer timer=new Timer();
TimerTask task = new TimerTask(){
public void run(){
}
};
long delaytime=8000;//即為8秒
timer .schedule(task,delaytime);
在倒計時時間 delaytime 結束後 會觸發 Timertask 中的 run() 方法
3、ScheduledExecutorService 實作定時器
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
//定期執行
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("delay 3 seconds, and excute every 2 seconds");
}
},3,2,TimeUnit.SECONDS); //表示延遲3秒後每2秒執行一次;ScheduledExecutorService比Timer更安全,功能更強大
Timer 使用注意:
1、多個TimerTask 可以共用一個Timer,也就是說Timer對象調用一次schedule方法就是建立了一個線程。當Timer執行cancel() 方法後,所有的TimerTask線程都被終止
eg:
private Timer timer = new Timer();
class MyTimerTask extends TimerTask{
private String taskName;
public MyTimerTask(String taskname){
this.taskName = taskname;
}
@Override
public void run() {
for (int i=1;i<4;i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i("test",taskName + "---"+"第 "+i+" 次");
}
}
}
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "hello button", Toast.LENGTH_SHORT).show();
TimerTask t1 = new MyTimerTask("timerTask1");
TimerTask t2 = new MyTimerTask("timerTask2");
timer.schedule(t1,0);
timer.schedule(t2,0);
}
});
運作結果如下:
09-26 19:15:49.631 4494-4522/com.example.zhan.test I/test: timerTask1---第 1 次
09-26 19:15:50.634 4494-4522/com.example.zhan.test I/test: timerTask1---第 2 次
09-26 19:15:51.635 4494-4522/com.example.zhan.test I/test: timerTask1---第 3 次
09-26 19:15:52.635 4494-4522/com.example.zhan.test I/test: timerTask2---第 1 次
09-26 19:15:53.635 4494-4522/com.example.zhan.test I/test: timerTask2---第 2 次
09-26 19:15:54.636 4494-4522/com.example.zhan.test I/test: timerTask2---第 3 次
從上可以看到,t1,t2的執行時有順序的,且t2在t1執行結束後才接着執行
而如果在t1 、 t2 運作的中途調用 cancel 方法,則會取消所有的線程操作。