CountDownTimer 实现倒计时功能

CountDownTimer

CountDownTimer 是android 自带的一个倒计时类,使用这个类可以很简单的实现 倒计时功能

CountDownTimer 的实现方式

1 new CountDownTimer(6000,1000) {//第一个参数表示的是倒计时的总时间,第二参数表示的是倒计时的间隔时间。 2 @Override 3 public void onTick(long millisUntilFinished) {//倒计时的过程 4 textView.setText(millisUntilFinished / 1000 + "秒"); 5 } 6 7 @Override 8 public void onFinish() {//倒计时结束 9 textView.setText("倒计时结束"); 10 } 11 }.start();

实现效果

实现效果

取消计时器

调用 CountDownTimer 的 cancel() 方法,可以为我们取消计时器:但是这个方法,只有在 android 5.0 以上才有效果,在android 5.0 以下并没有效果。如果需要在android 5.0 以下的系统中也使用 cancel,需要我们自己根据 CountDownTimer 源码中的 实现方式,重新实现一下。 cancel()源码

1 /** 2 * Cancel the countdown. 3 */ 4 public synchronized final void cancel() { 5 mCancelled = true; 6 mHandler.removeMessages(MSG); 7 } 8 9 10 private static final int MSG = 1; 11 12 13 // handles counting down 14 private Handler mHandler = new Handler() { 15 16 @Override 17 public void handleMessage(Message msg) { 18 19 synchronized (CountDownTimer.this) { 20 if (mCancelled) { 21 return; 22 } 23 24 final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime(); 25 26 if (millisLeft <= 0) { 27 onFinish(); 28 } else if (millisLeft < mCountdownInterval) { 29 // no tick, just delay until done 30 sendMessageDelayed(obtainMessage(MSG), millisLeft); 31 } else { 32 long lastTickStart = SystemClock.elapsedRealtime(); 33 onTick(millisLeft); 34 35 // take into account user's onTick taking time to execute 36 long delay = lastTickStart + mCountdownInterval - SystemClock.elapsedRealtime(); 37 38 // special case: user's onTick took more than interval to 39 // complete, skip to next interval 40 while (delay < 0) delay += mCountdownInterval; 41 42 sendMessageDelayed(obtainMessage(MSG), delay); 43 } 44 } 45 } 46 };

由于在 android 5.0以上 增加了一个

 private boolean mCancelled = false;

所以我们只需要在 5.0 以下的系统中,去掉

1 if (mCancelled) { 2 return; 3 }

去掉这个判断即可。

点赞
收藏

评论区

加载中...

相关推荐

java线程

倒计时器CountDownLatch使用个例publicclassTest{staticfinalCountDownLatchendnewCountDownLatch(10);staticclassCounDownLatchDemo

「组件」倒计时

1:在components文件夹下新建CountDown.vuejs<template<p{{time}}</p</template<scriptexportdefault{data(){return{time:'',

Java并发系列5

今天讲一个倒计时器工具,叫CountDownLatch。需要这个工具的场景大概有:当所有的小任务都完成之后,再启动大任务。先看代码:publicclassCountDownLatchDemo{staticfinalCountDownLatchLATCHnewCountDownLatch(10);

【UE4官方案列学习】在UE4使用计时器实现一个倒计时事件(定时生成物体)

UE4Version:4.27.0VisualStudio201916.10.2在UE4使用计时器实现一个倒计时事件.h文件定义pragmaonceinclude"CoreMinimal.h"include"GameFramework/Actor.h"include"Components/TextRenderComponent.h"i

mysql中时间比较的实现

MySql中时间比较的实现unix\_timestamp()unix\_timestamp函数可以接受一个参数,也可以不使用参数。它的返回值是一个无符号的整数。不使用参数,它返回自1970年1月1日0时0分0秒到现在所经过的秒数,如果使用参数,参数的类型为时间类型或者时间类型的字符串表示,则是从1970010100:00:0

CountDownLatch和CylicBarrier以及Semaphare你使用过吗

CountDownLatch是什么CountDownLatch的字面意思:倒计时门栓它的功能是:让一些线程阻塞直到另一些线程完成一系列操作后才唤醒。它通过调用await方法让线程进入阻塞状态等待倒计时0时唤醒。它通过线程调用countDown方法让倒计时中的计数器减去1,当计数器为0时,会唤醒哪些因为调用了await而阻塞的线程。