android计时器类CountDownTime的运用及扩展

本文介绍如何在Android中实现一个具备倒计时、暂停、继续和快进快退功能的自定义倒计时器类,通过继承并扩展Android自带的CountdownTimer类来满足特定需求。

最近需要一个倒数计时器,要求实现倒数计时,暂停,继续,和快进快退的功能。Android本身提供了一个CountdownTimer的类,采用Handler的方式实现,但是只提供了倒数计时的功能,对于暂停,继续,快进快退功能未提供支持,于是在CounterDownTimer的基础上重写了一个类,最终满足要求。

Java代码  收藏代码
  1. import android.os.Handler;  
  2. import android.os.Message;  
  3.   
  4. public abstract class AdvancedCountdownTimer {  
  5.   
  6.     private final long mCountdownInterval;  
  7.   
  8.     private long mTotalTime;  
  9.   
  10.     private long mRemainTime;  
  11.   
  12.       
  13.     public AdvancedCountdownTimer(long millisInFuture, long countDownInterval) {  
  14.         mTotalTime = millisInFuture;  
  15.         mCountdownInterval = countDownInterval;  
  16.   
  17.         mRemainTime = millisInFuture;  
  18.     }  
  19.   
  20.     public final void seek(int value) {  
  21.         synchronized (AdvancedCountdownTimer.this) {  
  22.             mRemainTime = ((100 - value) * mTotalTime) / 100;  
  23.         }  
  24.     }  
  25.   
  26.       
  27.     public final void cancel() {  
  28.         mHandler.removeMessages(MSG_RUN);  
  29.         mHandler.removeMessages(MSG_PAUSE);  
  30.     }  
  31.   
  32.     public final void resume() {  
  33.         mHandler.removeMessages(MSG_PAUSE);  
  34.         mHandler.sendMessageAtFrontOfQueue(mHandler.obtainMessage(MSG_RUN));  
  35.     }  
  36.   
  37.     public final void pause() {  
  38.         mHandler.removeMessages(MSG_RUN);  
  39.         mHandler.sendMessageAtFrontOfQueue(mHandler.obtainMessage(MSG_PAUSE));  
  40.     }  
  41.   
  42.       
  43.     public synchronized final AdvancedCountdownTimer start() {  
  44.         if (mRemainTime <= 0) {  
  45.             onFinish();  
  46.             return this;  
  47.         }  
  48.         mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_RUN),  
  49.                 mCountdownInterval);  
  50.         return this;  
  51.     }  
  52.   
  53.     public abstract void onTick(long millisUntilFinished, int percent);  
  54.   
  55.       
  56.     public abstract void onFinish();  
  57.   
  58.     private static final int MSG_RUN = 1;  
  59.     private static final int MSG_PAUSE = 2;  
  60.   
  61.     private Handler mHandler = new Handler() {  
  62.   
  63.         @Override  
  64.         public void handleMessage(Message msg) {  
  65.   
  66.             synchronized (AdvancedCountdownTimer.this) {  
  67.                 if (msg.what == MSG_RUN) {  
  68.                     mRemainTime = mRemainTime - mCountdownInterval;  
  69.   
  70.                     if (mRemainTime <= 0) {  
  71.                         onFinish();  
  72.                     } else if (mRemainTime < mCountdownInterval) {  
  73.                         sendMessageDelayed(obtainMessage(MSG_RUN), mRemainTime);  
  74.                     } else {  
  75.   
  76.                         onTick(mRemainTime, new Long(100  
  77.                                 * (mTotalTime - mRemainTime) / mTotalTime)  
  78.                                 .intValue());  
  79.   
  80.                       
  81.                         sendMessageDelayed(obtainMessage(MSG_RUN),  
  82.                                 mCountdownInterval);  
  83.                     }  
  84.                 } else if (msg.what == MSG_PAUSE) {  
  85.   
  86.                 }  
  87.             }  
  88.         }  
  89.     };  
  90. }  


android自带的CountdownTimer源码: 
Java代码  收藏代码
  1. /** 
  2.  * Copyright (C) 2008 The Android Open Source Project 
  3.  * 
  4.  * Licensed under the Apache License, Version 2.0 (the "License"); 
  5.  * you may not use this file except in compliance with the License. 
  6.  * You may obtain a copy of the License at 
  7.  * 
  8.  *      http://www.apache.org/licenses/LICENSE-2.0 
  9.  * 
  10.  * Unless required by applicable law or agreed to in writing, software 
  11.  * distributed under the License is distributed on an "AS IS" BASIS, 
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  13.  * See the License for the specific language governing permissions and 
  14.  * limitations under the License. 
  15.  */  
  16.   
  17. package android.os;  
  18.   
  19. import android.util.Log;  
  20.   
  21. /*** 
  22.  * Schedule a countdown until a time in the future, with 
  23.  * regular notifications on intervals along the way. 
  24.  * 
  25.  * Example of showing a 30 second countdown in a text field: 
  26.  * 
  27.  * <pre class="prettyprint"> 
  28.  * new CountdownTimer(30000, 1000) { 
  29.  * 
  30.  *     public void onTick(long millisUntilFinished) { 
  31.  *         mTextField.setText("seconds remaining: " + millisUntilFinished / 1000); 
  32.  *     } 
  33.  * 
  34.  *     public void onFinish() { 
  35.  *         mTextField.setText("done!"); 
  36.  *     } 
  37.  *  }.start(); 
  38.  * </pre> 
  39.  * 
  40.  * The calls to {@link #onTick(long)} are synchronized to this object so that 
  41.  * one call to {@link #onTick(long)} won't ever occur before the previous 
  42.  * callback is complete.  This is only relevant when the implementation of 
  43.  * {@link #onTick(long)} takes an amount of time to execute that is significant 
  44.  * compared to the countdown interval. 
  45.  */  
  46. public abstract class CountDownTimer {  
  47.   
  48.     /*** 
  49.      * Millis since epoch when alarm should stop. 
  50.      */  
  51.     private final long mMillisInFuture;  
  52.   
  53.     /*** 
  54.      * The interval in millis that the user receives callbacks 
  55.      */  
  56.     private final long mCountdownInterval;  
  57.   
  58.     private long mStopTimeInFuture;  
  59.   
  60.     /*** 
  61.      * @param millisInFuture The number of millis in the future from the call 
  62.      *   to {@link #start()} until the countdown is done and {@link #onFinish()} 
  63.      *   is called. 
  64.      * @param countDownInterval The interval along the way to receive 
  65.      *   {@link #onTick(long)} callbacks. 
  66.      */  
  67.     public CountDownTimer(long millisInFuture, long countDownInterval) {  
  68.         mMillisInFuture = millisInFuture;  
  69.         mCountdownInterval = countDownInterval;  
  70.     }  
  71.   
  72.     /*** 
  73.      * Cancel the countdown. 
  74.      */  
  75.     public final void cancel() {  
  76.         mHandler.removeMessages(MSG);  
  77.     }  
  78.   
  79.     /*** 
  80.      * Start the countdown. 
  81.      */  
  82.     public synchronized final CountDownTimer start() {  
  83.         if (mMillisInFuture <= 0) {  
  84.             onFinish();  
  85.             return this;  
  86.         }  
  87.         mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;  
  88.         mHandler.sendMessage(mHandler.obtainMessage(MSG));  
  89.         return this;  
  90.     }  
  91.   
  92.   
  93.     /*** 
  94.      * Callback fired on regular interval. 
  95.      * @param millisUntilFinished The amount of time until finished. 
  96.      */  
  97.     public abstract void onTick(long millisUntilFinished);  
  98.   
  99.     /*** 
  100.      * Callback fired when the time is up. 
  101.      */  
  102.     public abstract void onFinish();  
  103.   
  104.   
  105.     private static final int MSG = 1;  
  106.   
  107.   
  108.     // handles counting down  
  109.     private Handler mHandler = new Handler() {  
  110.   
  111.         @Override  
  112.         public void handleMessage(Message msg) {  
  113.   
  114.             synchronized (CountDownTimer.this) {  
  115.                 final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();  
  116.   
  117.                 if (millisLeft <= 0) {  
  118.                     onFinish();  
  119.                 } else if (millisLeft < mCountdownInterval) {  
  120.                     // no tick, just delay until done  
  121.                     sendMessageDelayed(obtainMessage(MSG), millisLeft);  
  122.                 } else {  
  123.                     long lastTickStart = SystemClock.elapsedRealtime();  
  124.                     onTick(millisLeft);  
  125.   
  126.                     // take into account user's onTick taking time to execute  
  127.                     long delay = lastTickStart + mCountdownInterval - SystemClock.elapsedRealtime();  
  128.   
  129.                     // special case: user's onTick took more than interval to  
  130.                     // complete, skip to next interval  
  131.                     while (delay < 0) delay += mCountdownInterval;  
  132.   
  133.                     sendMessageDelayed(obtainMessage(MSG), delay);  
  134.                 }  
  135.             }  
  136.         }  
  137.     };  
  138. }  


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值