Android 倒计时——Timer和CountDownTimer的使用,实现启动,暂停,继续,重复,重设时长以及启动service后台倒计时

实现效果

单个倒计时功能                                                                                 列表倒计时功能

   

 

自定义倒计时类

public class CountDownTimerSupport implements ITimerSupport {private Timer mTimer;private Handler mHandler;/*** 倒计时时间*/private long mMillisInFuture;/*** 间隔时间*/private long mCountDownInterval;/*** 倒计时剩余时间*/private long mMillisUntilFinished;private OnCountDownTimerListener mOnCountDownTimerListener;private TimerState mTimerState = TimerState.FINISH;@Deprecatedpublic CountDownTimerSupport() {this.mHandler = new Handler();}public CountDownTimerSupport(long millisInFuture, long countDownInterval) {this.setMillisInFuture(millisInFuture);this.setCountDownInterval(countDownInterval);this.mHandler = new Handler();}@Overridepublic void start() {//防止重复启动 重新启动要先reset再startif (mTimer == null && mTimerState != TimerState.START) {mTimer = new Timer();mTimer.scheduleAtFixedRate(createTimerTask(), 0, mCountDownInterval);mTimerState = TimerState.START;}}@Overridepublic void pause() {if (mTimer != null && mTimerState == TimerState.START) {cancelTimer();mTimerState = TimerState.PAUSE;}}@Overridepublic void resume() {if (mTimerState == TimerState.PAUSE) {start();}}@Overridepublic void stop() {if (mTimer != null) {cancelTimer();mMillisUntilFinished = mMillisInFuture;mTimerState = TimerState.FINISH;mHandler.post(new Runnable() {@Overridepublic void run() {if (mOnCountDownTimerListener != null) {mOnCountDownTimerListener.onFinish();}}});}}@Overridepublic void reset() {if (mTimer != null) {cancelTimer();}mMillisUntilFinished = mMillisInFuture;mTimerState = TimerState.FINISH;}private void cancelTimer() {mTimer.cancel();mTimer.purge();mTimer = null;}public boolean isStart() {return mTimerState == TimerState.START;}public boolean isFinish() {return mTimerState == TimerState.FINISH;}/*** @deprecated 使用构造方法* @param millisInFuture*/@Deprecatedpublic void setMillisInFuture(long millisInFuture) {this.mMillisInFuture = millisInFuture;this.mMillisUntilFinished = mMillisInFuture;}/*** @deprecated 使用构造方法* @param countDownInterval*/@Deprecatedpublic void setCountDownInterval(long countDownInterval) {this.mCountDownInterval = countDownInterval;}public void setOnCountDownTimerListener(OnCountDownTimerListener listener) {this.mOnCountDownTimerListener = listener;}public long getMillisUntilFinished() {return mMillisUntilFinished;}public TimerState getTimerState() {return mTimerState;}/*** @param millisInFuture* @param countDownInterval* @return* @deprecated 已更换Timer*/@Deprecatedprotected CountDownTimer createCountDownTimer(long millisInFuture, long countDownInterval) {return null;}protected TimerTask createTimerTask() {return new TimerTask() {private long startTime = -1;@Overridepublic void run() {if (startTime < 0) {//第一次回调 记录开始时间startTime = scheduledExecutionTime() - (mMillisInFuture - mMillisUntilFinished);mHandler.post(new Runnable() {@Overridepublic void run() {if (mOnCountDownTimerListener != null) {mOnCountDownTimerListener.onTick(mMillisUntilFinished);}}});} else {//剩余时间mMillisUntilFinished = mMillisInFuture - (scheduledExecutionTime() - startTime);mHandler.post(new Runnable() {@Overridepublic void run() {if (mOnCountDownTimerListener != null) {mOnCountDownTimerListener.onTick(mMillisUntilFinished);}}});if (mMillisUntilFinished <= 0) {//如果没有剩余时间 就停止stop();}}}};}}

2、初始化

private CountDownTimerSupport mTimer;
 mTimer = new CountDownTimerSupport(duration * 1000, 1000);

 

        mTimer.setOnCountDownTimerListener(new OnCountDownTimerListener() {@Overridepublic void onTick(long millisUntilFinished) {tv.setText(millisUntilFinished + "ms\n" + millisUntilFinished / 1000 + "s");//倒计时
//                    textView.setText((60 * 1000 - millisUntilFinished) / 1000 + "S");//正计时Log.d("CountDownTimerSupport", "onTick : " + millisUntilFinished + "ms");}@Overridepublic void onFinish() {tv.setText("已停止");Log.d("CountDownTimerSupport", "onFinish");}});

启动

mTimer.start();

暂停

mTimer.pause();

继续

mTimer.resume();

停止

mTimer.stop();

重复启动,重设时长

            mTimer.reset();//重复启动
//            mTimer.setMillisInFuture(30000);//重设时长mTimer.start();//重复启动

 

// 发送带有数据的广播
private void broadcastUpdate(final String action, String time) {final Intent intent = new Intent(action);intent.putExtra("time", time);sendBroadcast(intent);
}
//        发送广播方法——更新倒计时broadcastUpdate(IN_RUNNING, time / 1000 + "");//        关闭服务,停止倒计时Intent countDownIntent = new Intent(MainActivity.this, CodeTimerService.class);stopService(countDownIntent);finish();

 

实现demo: https://download.csdn.net/download/meixi_android/12484271

bug在线交流:QQ1085220040 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/414398.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

cin和scanf读入速度

cin慢是有原因的&#xff0c;其实默认的时候&#xff0c;cin与stdin总是保持同步的&#xff0c;也就是说这两种方法可以混用&#xff0c;而不必担心文件指针混乱&#xff0c;同时cout和stdout也一样&#xff0c;两者混用不会输出顺序错乱。正因为这个兼容性的特性&#xff0c;导…

03-Flutter移动电商实战-底部导航栏制作

03-Flutter移动电商实战-底部导航栏制作 1、cupertino_IOS风格介绍 在Flutter里是有两种内置风格的&#xff1a; material风格&#xff1a; Material Design 是由 Google 推出的全新设计语言&#xff0c;这种设计语言是为手机、平板电脑、台式机和其他平台提供一致&#xff…

plugin since you are using Gradle version 4.6 or above

Android studio项目在新的开发环境下打开时报错如下 解决方法如下&#xff1a; 1、目录选到Android状态 2、进入gradle.properties文件。 3、org.gradle.configureondemandfalse——————默认是true。改完false即可

[转]调试 smallcorgi/Faster-RCNN_TF 的demo过程遇到的问题

最近在调试faster R-CNN时&#xff0c;遇到了各种各样的问题。使用的算法库为https://github.com/smallcorgi/Faster-RCNN_TF 注&#xff1a;本文使用的是通过virtualenv 创建python虚拟环境进行调试&#xff0c;python 版本2.7&#xff0c;tensorflow 版本为tensorflow1.4-gpu…

04-Flutter移动电商实战-打通底部导航栏

04-Flutter移动电商实战-打通底部导航栏 关于界面切换以及底栏的实现可参考之前写的一篇文章&#xff1a;Flutter实 ViewPager、bottomNavigationBar界面切换 1、新建4个基本dart文件 在pages目录下&#xff0c;我们新建下面四个dart文件。 home_page.dart :商城首页UI页面…

【机器学习】--模型评估指标之混淆矩阵,ROC曲线和AUC面积

一、前述 怎么样对训练出来的模型进行评估是有一定指标的&#xff0c;本文就相关指标做一个总结。 二、具体 1、混淆矩阵 混淆矩阵如图&#xff1a; 第一个参数true&#xff0c;false是指预测的正确性。 第二个参数true,postitives是指预测的结果。 相关公式&#xff1a; 检测正…

05-Flutter移动电商实战-dio基础_引入和简单的Get请求

05-Flutter移动电商实战-dio基础_引入和简单的Get请求 这篇开始我们学习Dart第三方Http请求库dio&#xff0c;这是国人开源的一个项目&#xff0c;也是国内用的最广泛的Dart Http请求库。 1、dio介绍和引入 dio是一个强大的Dart Http请求库&#xff0c;支持Restful API、 Fo…

16进制转10进制,以及二进制负数的补码

String sixteen "D4"; int ten Integer.parseInt(sixteen, 16);byte value (byte) ten;//解决二进制补码String ss String.valueOf(value); int wd Integer.parseInt(ss);

Jmeter——for循环控制器和if逻辑控制器

有时我们不仅仅需要用例按照简单的顺序跑&#xff0c;需要内嵌循环&#xff0c;或者条件分支&#xff0c;让某些用例在满足一定条件时才执行。 1、for循环控制器 此处记录两种应用的场景&#xff0c;一种是直接定义好要循环的变量&#xff0c;循环次数是固定的&#xff0c;写死…

06-Flutter移动电商实战-dio基础_Get_Post请求和动态组件协作

06-Flutter移动电商实战-dio基础_Get_Post请求和动态组件协作 上篇文章中&#xff0c;我们只看到了 dio 的使用方式&#xff0c;但并未跟应用关联起来&#xff0c;所以这一篇将 dio 网络请求与应用界面结合起来&#xff0c;当然这也是为以后的实战作基础准备&#xff0c;基础打…

Cannot merge new index 66395 into a non-jumbo instruction!,uses or overrides a deprecated API.

老项目运行没问题。一打包就报错 解决方法——添加dexOptions android {compileSdkVersion 27dexOptions{jumboMode true}

localStorage和sessionStorage的简单使用

localStorage和sessionStorage是Web提供的两种本地存储方式。 相比较cookie而言&#xff0c;localStorage和sessionStorage的存储大小很大&#xff0c;localStorage能够长期保存&#xff0c;sessionStorage在会话期间保存。 localStorage用法&#xff1a; 1.设置&#xff1a; v…

08-Flutter移动电商实战-dio基础_伪造请求头获取数据

08-Flutter移动电商实战-dio基础_伪造请求头获取数据 在很多时候&#xff0c;后端为了安全都会有一些请求头的限制&#xff0c;只有请求头对了&#xff0c;才能正确返回数据。这虽然限制了一些人恶意请求数据&#xff0c;但是对于我们聪明的程序员来说&#xff0c;就是形同虚设…

工作269:uni--客流分析优化

<template><view><view><view id"main"><!-- 第一步 设置盒子大小 --></view></view><view><view v-for"(item,index) in 10"><view style"display: flex;justify-content: space-between;…

No virtual method diskCacheStrategy

android运行时错误。报错如下&#xff1a; java.lang.NoSuchMethodError: No virtual method diskCacheStrategy(Lcom/bumptech/glide/load/engine/DiskCacheStrategy;)Lcom/bumptech/glide/request/BaseRequestOptions; in class Lcom/bumptech/glide/request/RequestOptions…

工作270:el-dialog的open回调

<el-dialog open"DepartThrow" title"新建部门" :visible.sync"dialogFormVisible" close"close"><el-form ref"form" :rules"rules" :model"form" size"medium" v-loading"lo…

09-Flutter移动电商实战-移动商城数据请求实战

09-Flutter移动电商实战-移动商城数据请求实战 1、URL接口管理文件建立 第一步需要在建立一个URL的管理文件&#xff0c;因为课程的接口会一直进行变化&#xff0c;所以单独拿出来会非常方便变化接口。当然工作中的URL管理也是需要这样配置的&#xff0c;以为我们会不断的切换…

栈和队列的区别,栈和堆的区别

栈和队列的区别&#xff1a; 栈的插入和删除操作都是在一端进行的&#xff0c;而队列的操作却是在两端进行的。 栈是先进后出&#xff0c;队列是先进先出。 栈只允许在表尾一端进行插入和删除&#xff0c;队列只允许在表尾一端进行插入&#xff0c;在表头一端进行删除。 栈和堆…