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 方法,则会取消所有的线程操作。
