使用CountDownTimer类轻松实现倒计时功能

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!
//┃   ┗━━━┓
//┃       ┣┓
//┃       ┏┛
//┗┓┓┏━┳┓┏┛
// ┃┫┫ ┃┫┫
// ┗┻┛ ┗┻┛

布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  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" > 

  <TextView
    android:id="@+id/show"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" /> 

  <Button
    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" /> 

  <Button
    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" /> 

</RelativeLayout>

附:
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);
        }
      }
    }
  };
}
(0)

相关推荐

  • Android CountDownTimer实现倒计时器

    使用介绍 开发中经常会遇到一些和倒计时有关的场景,比如发送验证码的按钮,会在点击发送后,显示倒计时间,倒计时结束后才能够刷新按钮,再次允许点击.为了不阻塞软件的运行,又要实时刷新界面,我们通常会用到 Handler 或者 AsyncTask 等技术,自己写逻辑实现.其实 Android 中已经封装好了一套 CountDownTimer 来实现这个功能需求. CountDownTimer(long millisInFuture, long countDownInterval) CountDownT

  • Android中CountDownTimer 实现倒计时功能

    CountDownTimer CountDownTimer 是android 自带的一个倒计时类,使用这个类可以很简单的实现 倒计时功能 CountDownTimer 的实现方式 new CountDownTimer(6000,1000) {//第一个参数表示的是倒计时的总时间,第二参数表示的是倒计时的间隔时间. @Override public void onTick(long millisUntilFinished) {//倒计时的过程 textView.setText(millisUnti

  • Android中使用Handler及Countdowntimer实现包含倒计时的闪屏页面

    上一篇博文<Android中Handler使用浅析>通过实现倒计时闪屏页面的制作引出了Handler的使用方法以及实现原理,博文末尾也提到了实现过程中的Bug,有兴趣的朋友可以点击链接回去看看.今天通过使用Handler以及CountDownTimer来实现完整版的倒计时闪屏(不会出现在退出闪屏页后,依然会跳转页面的现象). 1. 实现效果如下: 1.1  正常进入跳转的效果以及log显示 1.2  倒计时未结束时退出以及log显示 对比上篇博文的实现,退出后计时停止且不会再跳到新的界面 2.

  • Android利用CountDownTimer实现点击获取验证码倒计时效果

    本文实例为大家分享了Android点击获取验证码倒计时的具体代码,供大家参考,具体内容如下 package com.loaderman.countdowntimerdemo; import android.os.Bundle; import android.os.CountDownTimer; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextV

  • Android基于CountDownTimer实现倒计时功能

    本文实例讲述了Android编程基于CountDownTimer实现倒计时功能的方法.分享给大家供大家参考,具体如下: 在逛论坛的时候,看到一个网友提问,说到了CountDownTimer这个类,从名字上面大家就可以看出来,记录下载时间.将后台线程的创建和Handler队列封装成一个方便的类调用. 查看了一下官方文档,这个类及其简单,只有四个方法,上面都涉及到了onTick,onFinsh.cancel和start.其中前面两个是抽象方法,所以要重写一下. 下面是官方给的一个小例子: new C

  • Android使用CountDownTimer实现倒计时效果

    在开发中会经常用到倒计时这个功能,包括给手机发送验证码等等,之前我的做法都是使用Handler + Timer + TimerTask来实现,现在发现了这个类,果断抛弃之前的做法,相信还是有很多人和我一样一开始不知道Android已经帮我们封装好了一个叫CountDownTimer的类. 从字面上就可以看出来它叫倒数计时器又称定时器或计时器,采用Handler的方式实现,将后台线程的创建和Handler队列封装而成. 看了一下源码,发现这个类的调用还蛮简单,只有四个方法: (1)public a

  • Android中CountDownTimer倒计时器用法实例

    本文实例讲述了Android中CountDownTimer倒计时器用法.分享给大家供大家参考,具体如下: 在平时我们编程的时候,经常会用到倒计时这个功能,很多人不知道Android已经帮封装好了一个类,往往都自己写.现在发现了这个类,大家共享一下: 在一个TextView不断显示剩下的时间,代码如下: private TextView vertifyView; private CountDownTimer timer = new CountDownTimer(10000, 1000) { @Ov

  • 使用CountDownTimer类轻松实现倒计时功能

    CountDownTimer由系统提供 查资料的时候 发现了CountDownTimer这个类之后 果断抛弃了以前的倒计时做法 功能: 30秒倒计时 每次间隔1秒 参数: mc.start();方法开始 mc.cancel();方法结束 new MyCountDownTimer(30000, 1000); 第一个参数表示 总的时间为30000毫秒,间隔1000毫秒 直接上代码: package com.example.daojishi; import android.app.Activity;

  • Android使用CountDownTimer类实现倒计时闹钟

    下面使用CountDownTimer类实现倒计时小闹钟,CountDownTimer类其实很简单,一般只需重写其onFinish和onTick方法就可以实现倒计时小闹钟,代码如下: MainActivity: package com.home.brewclock; import android.app.Activity; import android.media.MediaPlayer; import android.os.Bundle; import android.os.CountDownT

  • IOS实现验证码倒计时功能(一)

    验证码倒计时按钮的应用是非常普遍的,该Blog就和你一起来写一个IDCountDownButton来实现验证码倒计时的效果.你可以想使用普通的UIButton类型按钮一样,只需要设置其倒计时时长(若未设置,默认为60秒),就可以轻松的实现点击countDownButton开始倒计时,倒计时结束方可重新点击. 一.实现效果 如图 二.实现思路 1.自定义一个IDCountDownButton,重写 beginTrackingWithTouch:withEvent: 拦截button的点击事件,根据

  • Android实现发送短信验证码倒计时功能示例

    一.简介: 开发中在用户注册或找回密码之类的功能,经常会遇到获取短信验证码,获取验证码后需要等待1分钟倒计时,这段时间是不能再次发送短信请求的. 效果图: 二.实现步骤: 1.一个关键类:CountDownTimer(Android系统自带的倒计时功能类) public class CountDownTimerUtils extends CountDownTimer { private TextView mTextView; //显示倒计时的文字 /** * @param textView Th

  • Android实现获取验证码倒计时功能

    本文实例为大家分享了android获取验证码倒计时功能的具体代码,供大家参考,具体内容如下 获取验证码倒计时在现在的App中非常常见,他主要的功能点就是给TextView设置一个点击事件,但是当点击后或出现倒计时,在倒计时的时候点击是触发不了点击事件的. 等倒计时结束显示重新获取验证码的时候可以重新触发点击事件: 在真实的项目中一般都是设置一分钟,咱们这里就不设置那么长了,设置10秒: 首先说下我这个demo非常简单,工具类不用管,直接复制到项目中,只需要两步两行代码即可: 第一步:初始化工具类

  • Android CountDownTimer实现定时器和倒计时效果

    本文实例为大家分享了Android实现定时器和倒计时的具体代码,供大家参考,具体内容如下 直接上代码,相信都看得懂. Android已经帮封装好了一个类,只不过很多人不知道而已. 代码: public class SplashActivity extends BaseAppCompatActivity { @InjectView(R.id.ivBg) ImageView ivBg; @InjectView(R.id.tvSkip) TextView tvSkip; int[] imgs = ne

  • 基于Android实现答题倒计时功能

    讲一下我在做一个答题APP时涉及到倒计时时遇到的一个问题吧. 碎片(Fragment)+CountDownTimer组成的一个答题,其中遇到的一个问题就是,这个题的倒计时在你手动滑动下一个题的时候却用在了下一个题的时间 解决这个问题运用的就是懒加载来控制倒计时的开始和取消 首先你要先定义一个抽象类继承Fragment 再让你的答题那个碎片的Activity继承 package com.zking.sun.dao; import android.support.v4.app.Fragment; i

  • Android 简单封装获取验证码倒计时功能

    效果如下图所示: 如图所示的效果相信大家都不陌生,我们可以使用很多种方法去实现此效果,这里自己采用 CountDownTimer 定时器简单封装下此效果,方便我们随时调用. 首页先在 attrs.xml 中定义下所需的几个属性: <resources> <declare-styleable name="CountDownButton"> <attr name="millisinfuture" format="integer&q

随机推荐