参考:https://www.jianshu.com/p/4e5c0d58c90c

1.背景

    需要做一个考试时间的倒计时,自己也有想法,但还是不想重复造轮子,直到发现除了timer之外,android还有一个

CountDownTimer。

2.效果图

3.代码

package mvp.study.skymobile.com.testandroidmethod.view;import android.os.CountDownTimer;/** * Author:boshuai.li * Time:2020/3/17   11:42 * Description: 倒计时的工具类 */public class PeterTimeCountRefresh extends CountDownTimer {    private OnTimerFinishListener finishListener;    private OnTimerProgressListener progressListener;    /**     * @param millisInFuture    分钟转换成 毫秒     * @param countDownInterval 计时的时间间隔     */    public PeterTimeCountRefresh(long millisInFuture, long countDownInterval) {        super(millisInFuture, countDownInterval);//参数依次为总时长,和计时的时间间隔,要显示的按钮    }    @Override    public void onTick(long millisUntilFinished) {//计时过程显示        if (progressListener != null) {            progressListener.onTimerProgress(millisUntilFinished);        }    }    @Override    public void onFinish() {//计时完毕时触发        if (finishListener != null) {            finishListener.onTimerFinish();        }    }    /**     * 设置timer走完的回调     */    public void setOnTimerFinishListener(OnTimerFinishListener finishListener) {        this.finishListener = finishListener;    }    /**     * 设置监听进度的     */    public void setOnTimerProgressListener(OnTimerProgressListener progressListener) {        this.progressListener = progressListener;    }    /**     * Timer 执行完成的回调     */    public interface OnTimerFinishListener {        void onTimerFinish();    }    /**     * Timer 进度的监听     */    public interface OnTimerProgressListener {        void onTimerProgress(long timeLong);    }}

4.使用方法

PeterTimeCountRefresh timer = new PeterTimeCountRefresh(musicDuration, 1000);timer.setOnTimerProgressListener(new PeterTimeCountRefresh.OnTimerProgressListener() {@Overridepublic void onTimerProgress(long timeLong) {String text = TimeUtils.parseDuration(timeLong);PLog.i("onTimerProgress timeLong = " + timeLong + ", text = " + text);tv.setText(text);}});timer.setOnTimerFinishListener(new PeterTimeCountRefresh.OnTimerFinishListener() {@Overridepublic void onTimerFinish() {PLog.i("onTimerFinish enter");}});timer.start();

5.总结

    缺点在不支持暂停和继续,只有取消操作,如果想拓展的小伙伴,可以额外增加一下功能。源码很简单,有兴趣的小伙伴也可以研究下,很有好处的。

更多相关文章

  1. android短信拦截
  2. android 监听USB连接状态
  3. Android(安卓)实现闪屏页和右上角的倒计时跳转
  4. Android(安卓)剪切板监听
  5. Android中实现ListView滑动首字母提示 .
  6. 其他小知识点
  7. 其他小知识点
  8. fullScreen时的软键盘监听(非重写Layout方式)
  9. android 传统蓝牙开发 (附示例源码)

随机推荐

  1. Android 异步更新UI----AsyncTask
  2. Android中的悬浮对话框和即点即关对话框
  3. android Looper、Handler和MessageQueue
  4. 推荐10个Android开源项目
  5. android opencv 前置摄像头
  6. Android的TextView
  7. Android 使用TextView实现跑马灯效果
  8. Android中插件开发篇之----应用换肤原理
  9. Android 设置dialog背景全透明无边框
  10. Android ELF文件PLT和GOT