android实现倒计时计数,Android开发CountDownTimer轻松实现倒计时功能的方法-程序员宅基地

技术标签: android实现倒计时计数  

释放双眼,带上耳机,听听看~!

CountDownTimer由系统提供

查资料的时候 发现了CountDownTimer这个类之后 果断抛弃了以前的倒计时做法

功能:

30秒倒计时 每次间隔1秒

参数:

mc.start();方法开始

mc.cancel();方法结束

new MyCountDownTimer(30000, 1000); 第一个参数表示 总的时间为30000毫秒,间隔1000毫秒

直接上代码:

package com.example.daojishi;

import android.app.Activity;

import android.os.Bundle;

import android.os.CountDownTimer;

import android.util.Log;

import android.view.View;

import android.widget.TextView;

import android.widget.Toast;

/**

*

* @author baozi

*

* 倒计时的类 CountDownTimer

*

*/

public class MainActivity extends Activity {

private MyCountDownTimer mc;

private TextView tv;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

tv = (TextView) findViewById(R.id.show);

mc = new MyCountDownTimer(30000, 1000);

mc.start();

}

public void oncancel(View view) {

Toast.makeText(MainActivity.this, "取消", Toast.LENGTH_LONG).show();// toast有显示时间延迟

mc.cancel();

}

public void restart(View view) {

Toast.makeText(MainActivity.this, "重新开始", Toast.LENGTH_LONG).show();// toast有显示时间延迟

mc.start();

}

/**

* 继承 CountDownTimer 防范

*

* 重写 父类的方法 onTick() 、 onFinish()

*/

class MyCountDownTimer extends CountDownTimer {

/**

*

* @param millisInFuture

* 表示以毫秒为单位 倒计时的总数

*

* 例如 millisInFuture=1000 表示1秒

*

* @param countDownInterval

* 表示 间隔 多少微秒 调用一次 onTick 方法

*

* 例如: countDownInterval =1000 ; 表示每1000毫秒调用一次onTick()

*

*/

public MyCountDownTimer(long millisInFuture, long countDownInterval) {

super(millisInFuture, countDownInterval);

}

@Override

public void onFinish() {

tv.setText("done");

}

@Override

public void onTick(long millisUntilFinished) {

Log.i("MainActivity", millisUntilFinished + "");

tv.setText("倒计时(" + millisUntilFinished / 1000 + ")...");

}

}

}

//┏┓   ┏┓

//┏┛┻━━━┛┻┓

//┃       ┃

//┃   ━   ┃

//┃ ┳┛ ┗┳ ┃

//┃       ┃

//┃   ┻   ┃

//┃       ┃

//┗━┓   ┏━┛

//┃   ┃ 神兽保佑

//┃   ┃ 代码无BUG!

//┃   ┗━━━┓

//┃       ┣┓

//┃       ┏┛

//┗┓┓┏━┳┓┏┛

// ┃┫┫ ┃┫┫

// ┗┻┛ ┗┻┛

布局:

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

tools:context=".MainActivity" >

android:id="@+id/show"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/hello_world" />

android:id="@+id/button1"

android:onClick="oncancel"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignLeft="@+id/show"

android:layout_below="@+id/show"

android:layout_marginLeft="50dp"

android:layout_marginTop="106dp"

android:text="cancel" />

android:id="@+id/button2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignLeft="@+id/button1"

android:layout_below="@+id/button1"

android:layout_marginTop="63dp"

android:onClick="restart"

android:text="restart" />

附:

CountDownTimer源码:

/*

* Copyright (C) 2008 The Android Open Source Project

*

* Licensed under the Apache License, Version 2.0 (the "License");

* you may not use this file except in compliance with the License.

* You may obtain a copy of the License at

*

* http://www.apache.org/licenses/LICENSE-2.0

*

* Unless required by applicable law or agreed to in writing, software

* distributed under the License is distributed on an "AS IS" BASIS,

* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

* See the License for the specific language governing permissions and

* limitations under the License.

*/

package android.os;

import android.util.Log;

/**

* Schedule a countdown until a time in the future, with

* regular notifications on intervals along the way.

*

* Example of showing a 30 second countdown in a text field:

*

*

* new CountDownTimer(30000, 1000) {

*

* public void onTick(long millisUntilFinished) {

* mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);

* }

*

* public void onFinish() {

* mTextField.setText("done!");

* }

* }.start();

*

*

* The calls to {@link #onTick(long)} are synchronized to this object so that

* one call to {@link #onTick(long)} won't ever occur before the previous

* callback is complete. This is only relevant when the implementation of

* {@link #onTick(long)} takes an amount of time to execute that is significant

* compared to the countdown interval.

*/

public abstract class CountDownTimer {

/**

* Millis since epoch when alarm should stop.

*/

private final long mMillisInFuture;

/**

* The interval in millis that the user receives callbacks

*/

private final long mCountdownInterval;

private long mStopTimeInFuture;

/**

* @param millisInFuture The number of millis in the future from the call

* to {@link #start()} until the countdown is done and {@link #onFinish()}

* is called.

* @param countDownInterval The interval along the way to receive

* {@link #onTick(long)} callbacks.

*/

public CountDownTimer(long millisInFuture, long countDownInterval) {

mMillisInFuture = millisInFuture;

mCountdownInterval = countDownInterval;

}

/**

* Cancel the countdown.

*/

public final void cancel() {

mHandler.removeMessages(MSG);

}

/**

* Start the countdown.

*/

public synchronized final CountDownTimer start() {

if (mMillisInFuture <= 0) {

onFinish();

return this;

}

mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;

mHandler.sendMessage(mHandler.obtainMessage(MSG));

return this;

}

/**

* Callback fired on regular interval.

* @param millisUntilFinished The amount of time until finished.

*/

public abstract void onTick(long millisUntilFinished);

/**

* Callback fired when the time is up.

*/

public abstract void onFinish();

private static final int MSG = 1;

// handles counting down

private Handler mHandler = new Handler() {

@Override

public void handleMessage(Message msg) {

synchronized (CountDownTimer.this) {

final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();

if (millisLeft <= 0) {

onFinish();

} else if (millisLeft < mCountdownInterval) {

// no tick, just delay until done

sendMessageDelayed(obtainMessage(MSG), millisLeft);

} else {

long lastTickStart = SystemClock.elapsedRealtime();

onTick(millisLeft);

// take into account user's onTick taking time to execute

long delay = lastTickStart + mCountdownInterval - SystemClock.elapsedRealtime();

// special case: user's onTick took more than interval to

// complete, skip to next interval

while (delay < 0) delay += mCountdownInterval;

sendMessageDelayed(obtainMessage(MSG), delay);

}

}

}

};

}

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_33212486/article/details/117514038

智能推荐

Java内存泄露监控工具:JVM监控工具介绍_java 内存图形监控泄露工具-程序员宅基地

文章浏览阅读223次。jstack -- 如果java程序崩溃生成core文件,jstack工具可以用来获得core文件的java stack和native stack的信息,从而可以轻松地知道java程序是如何崩溃和在程序何处发生问题。另外,jstack工具还可以附属到正在运行的java程序中,看到 当时运行的java程序的java stack和native stack的信息, 如果现在运行的java程序呈现hung_java 内存图形监控泄露工具

2018最新Web前端经典面试试题及答案_httpweb8888.one-程序员宅基地

文章浏览阅读1k次。本篇收录了一些面试中经常会遇到的经典面试题以及自己面试过程中遇到的一些问题,并且都给出了我在网上收集的答案。另外,宣传一下自己发布不久的一个前端vue的项目:基于vue2.0 +vuex+ element-ui后台管理系统。希望有兴趣的同学,可以一起共同..._httpweb8888.one

新型无线充电技术:能为人体植入设备充电_无线充电植入人体-程序员宅基地

文章浏览阅读2.2k次。原标题:无线充电技术获新突破 可给体内植入设备充电一项新的突破性的无线充电技术可以让新的健康跟踪监测工具更深地植入我们的体内——如肝脏、心脏,甚至大脑中。这项无线充电技术名为“中场无线传输”(mid-field wireless transfer),可以给深植入人体内的微型电子设备(如传感器、起搏器和神经刺激器)充电。它只要用一张信用卡大小的设备,就可以在体外对这些植入设备_无线充电植入人体

NIKE旗下品牌JORDAN发力新零售, 瞄准了天猫小黑盒-程序员宅基地

文章浏览阅读205次。8090一代,从小到大穿球鞋的时间,往多了说可能有20年,往少了大抵也得有个10年左右,但球鞋真正成了潮流圈口口相传的大众文化,还得是近几年的事情。当然,在这个有关鞋的文化里,还有一群更小众的群体——sneaker(sneaker,指热爱和收藏球鞋的人)。他们是sneaker文化的忠实追随者,他们眼中永恒的传奇,是Air Jordan。现如今,多了一个让万千sneaker欢欣的消息,他们终于可以在..._showcase jordan

opencv 图像梯度(python)_cv2.cv_64f-程序员宅基地

文章浏览阅读3.2k次,点赞6次,收藏20次。图像梯度图像梯度Sobel理论基础计算水平方向偏导数的近似值计算垂直方向偏导数的近似值Sobel算子及函数使用注意点:参数ddepth方向计算x方向和y方向的边缘叠加Scharr算子及函数使用Sobel算子和Scharr算子的比较Laplacian算子及函数使用算子总结图像梯度图像梯度计算的是图像变化的速度。对于图像的边缘部分,其灰度值变化较大,梯度值也较大;相反,对于图像中比较平滑的部分,其灰度值变化较小,相应的梯度值也较小。图像梯度计算需要求导数,但是图像梯度一般通过计算像素值的差来得到梯度的近_cv2.cv_64f

DataGrip 链接不上linux 上的mysql_在linux上安装了mysql在datagrip中连接后无法跟在finalshell中的数据同步-程序员宅基地

文章浏览阅读1.6k次。DataGrip 链接不上linux 上的mysql使用Centos7 linux上安装的MySQL 5.7.35安装步骤可参考 https://blog.csdn.net/qq_33554286/article/details/88357634安装完MySQL 若提示是这样的ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this stateme_在linux上安装了mysql在datagrip中连接后无法跟在finalshell中的数据同步

随便推点

Java整合kafka实现消费数据存入数据库_kafka消费数据入库-程序员宅基地

文章浏览阅读4.4k次,点赞9次,收藏20次。为了直观的显示效果,这里的配置均写死,生成环境中可写入配置。下面方法中除了创建【KafkaConsumer】的构造函数以外,还添加了订阅方法【subscribe】、消费消息方法【pool】、手动提交方法【commitSync】。然后线程运行时开始消费kafka,如果有返回值,则做进一步处理,其中用到了redis,可根据实际情况是否引用。其中消费消息方法的参数为【Duration】而不是【long】,查看源码得知参数为long的方法已弃用。这里主要将消费到的消息内容进行处理,然后创建一个延时队列。_kafka消费数据入库

SpringBoot的全局异常拦截_springboot全局异常拦截-程序员宅基地

文章浏览阅读1.9k次,点赞4次,收藏5次。在 Spring Boot 中,可以通过使用注解和注解来实现全局异常拦截。_springboot全局异常拦截

springboot 分页-程序员宅基地

文章浏览阅读3.1k次,点赞4次,收藏9次。springboot 分页1.创建新的page类,定义 pageNum 和 pageSize变量2.可以直接用别人写好的分页方法cntroller类下配置如下@RequestMapping("/CategoryThree/query") public String query(ModelMap modelMap, CategoryThreePage page){// List<CategoryThree> list = categoryThreeServic

【组件】前端js拖拽插件 VUE-程序员宅基地

文章浏览阅读2.2k次。Vue Draggable - Vue 拖拽组件王者Vue drag resize - 轻量级,无依赖,可缩放Vue smooth dnd - 简单动效,上下拖拽排序,涵盖多场景V-drag - 最简单的可拖拽执行方案Vue Easy DnD - 简洁快捷,上下拖拽场景适用Awe dnd - 基于 vue 2.x 拖放排序组件,元素和图片拖拽通用_js拖拽插件

编码和调制_编码与调制-程序员宅基地

文章浏览阅读2.3k次。目录信道信道的分类信道上传送的信号基带信号宽带信号编码与调制的概念数字数据编码为数字信号非归零编码(NRZ)曼彻斯特编码差分曼彻斯特编码归零编码(RZ)反向不归零编码(NRZI)4B/5B编码数字数据调制为模拟信号模拟数据编码为数字信号信道信号的传输媒介。一般用来表示向某一个方向传输信息的介质,因此一条通信线路往往包含一条发射信道和一条接收信道。信道的分类信道由其传输的信号可以分为模拟信道和数字信道,其中模拟信道用于传输模._编码与调制

5G时代下,Android音视频强势崛起,我们该如何快速入门音视频技术?-程序员宅基地

文章浏览阅读679次,点赞15次,收藏22次。在这里小编整理了一份Android大厂常见面试题,和一些Android架构视频解析,都已整理成文档,全部都已打包好了,希望能够对大家有所帮助,在面试中能顺利通过。喜欢本文的话,不妨顺手给我点个小赞、评论区留言或者转发支持一下呗本文已被CODING开源项目:《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》收录一个人可以走的很快,但一群人才能走的更远。如果你从事以下工作或对以下感兴趣,欢迎戳这里加入程序员的圈子,让我们一起学习成长!

推荐文章

热门文章

相关标签