在做一个功能的时候,用到了CountDownTimer,做为一个倒计时功能类,用起来挺方便的。然而,我想动态修改倒计时时间,发现竟然没有这个接口!
经过一阵鼓捣,发现可以有两种方案来实现。
1,通过反射;
2,重写CountDownTimer,添加上修改倒计时时间的接口。
下面分别描述:
1,通过反射,动态修改倒计时时间
我们知道,在CountDownTimer的构造函数中有两个参数,如下:
public CountDownTimer(long millisInFuture, long countDownInterval)
通过查看源码,可以知道,这两个参数,是这样使用的:
public CountDownTimer(long millisInFuture, long countDownInterval) {
mMillisInFuture = millisInFuture;
mCountdownInterval = countDownInterval;
}
很显然,接收参数的,就是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;
描述也很简洁,mMillisInFuture是从启动到停止的毫秒数,也就是执行完成的总时间间隔,执行完成后会调用onFinish方法;
mCountdownInterval是用户接收回调的间隔时间,单位也是毫秒,执行的回调方法是onTick。
找到它们了,剩下的事情就是反射了。
我做了两个函数,来分别设置这两个参数:
//利用反射动态地改变CountDownTimer类的私有字段mCountdownInterval
private void changeCountdownInterval(long time) {
try {
// 反射父类CountDownTimer的mCountdownInterval字段,动态改变回调频率
Class clazz = Class.forName("android.os.CountDownTimer");
Field field = clazz.getDeclaredField("mCountdownInterval");
//从Toast对象中获得mTN变量
field.setAccessible(true);
field.set(timethis, time);
} catch (Exception e) {
Log.e("Ye", "反射类android.os.CountDownTimer.mCountdownInterval失败:" + e);
}
}
//利用反射动态地改变CountDownTimer类的私有字段mMillisInFuture
private void changeMillisInFuture(long time) {
try {
// 反射父类CountDownTimer的mMillisInFuture字段,动态改变定时总时间
Class clazz = Class.forName("android.os.CountDownTimer");
Field field = clazz.getDeclaredField("mMillisInFuture");
field.setAccessible(true);
field.set(timethis, time);
} catch (Exception e) {
Log.e("Ye", "反射类android.os.CountDownTimer.mMillisInFuture失败: "+ e);
}
}
说明下,这里的timethis,是一个CountDownTimer对象,
timethis = new CountDownTimer(** * , ){...};
我这样定义,是避免定时器很快到时间了,导致异常,所以初始值定义到了一年这么长。其实,定义一个小间隔也没有问题,因为我们还没有启动定时器。
下面,就可以调用修改定时长度的函数了。
changeCountdownInterval(500);
changeMillisInFuture(timeOutSeconds * 1000);
timethis.start();
2,重写CountDownTimer,添加上修改倒计时时间的接口
代码如下:
package cn.timer;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
/* 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 CountDownTimerUtil {
/**
* Millis since epoch when alarm should stop.
*/
private long mMillisInFuture;
/**
* The interval in millis that the user receives callbacks
*/
private long mCountdownInterval;
private long mStopTimeInFuture;
private boolean mCancelled = false;
/**
* @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 CountDownTimerUtil(long millisInFuture, long countDownInterval) {
mMillisInFuture = millisInFuture;
mCountdownInterval = countDownInterval;
}
public final void setCountdownInterval(long countdownInterval) {
mCountdownInterval = countdownInterval;
}
public final void setMillisInFuture(long millisInFuture) {
mMillisInFuture = millisInFuture;
}
/**
* Cancel the countdown.
*
* Do not call it from inside CountDownTimer threads
*/
public final void cancel() {
mHandler.removeMessages(MSG);
mCancelled = true;
}
/**
* Start the countdown.
*/
public synchronized final CountDownTimerUtil start() {
if (mMillisInFuture <= ) {
onFinish();
return this;
}
mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
mHandler.sendMessage(mHandler.obtainMessage(MSG));
mCancelled = false;
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 = ;
// handles counting down
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
synchronized (CountDownTimerUtil.this) {
final long millisLeft = mStopTimeInFuture -
SystemClock.elapsedRealtime();
if (millisLeft <= ) {
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 < ) delay += mCountdownInterval;
if (!mCancelled) {
sendMessageDelayed(obtainMessage(MSG), delay);
}
}
}
}
};
}
调用代码如下:
创建实例:
timethis = new CountDownTimerUtil(** * , ){...};
在需要的时刻,进行动态修改:
timethis.setCountdownInterval();
timethis.setMillisInFuture(timeOutSeconds * );
timethis.start();
如果是创建后就修改,这样顺序的执行,其实也没有什么特殊的效果。能显示动态修改价值的地方,是在某种时刻执行,例如,在按钮点击时执行,动态修改就很有必要了。
参考文章:
http://www.cnblogs.com/yexiubiao/archive/2013/01/02/2842026.html
http://blog.csdn.net/liuweiballack/article/details/46605787