我需要一个倒数计时器,就像Android的CountDownTimer
一样,除了我需要它在达到零时进行注册然后继续进入底片。对此有优雅的解决方案吗?
答案 0 :(得分:0)
我找不到一个优雅的解决方案,所以我创建了一个。如果有更好的东西存在,或者您可能做出任何改进,请告诉我:
public abstract class NegativeCountDownTimer {
private final long millisInFuture;
private final long countDownInterval;
private CountDownTimer positiveCountDownTimer;
private Timer negativeTimer;
private long zeroMillisAt;
private boolean cancelled;
public NegativeCountDownTimer(long millisInFuture, long countDownInterval) {
this.millisInFuture = millisInFuture;
this.countDownInterval = countDownInterval;
}
public synchronized void cancel() {
if (positiveCountDownTimer != null) {
positiveCountDownTimer.cancel();
}
if (negativeTimer != null) {
negativeTimer.cancel();
}
cancelled = true;
}
public synchronized NegativeCountDownTimer start() {
cancelled = false;
positiveCountDownTimer = new CountDownTimer(millisInFuture, countDownInterval) {
@Override
public void onTick(long millisUntilFinished) {
if (cancelled) {
return;
}
onTickToc(millisUntilFinished);
}
@Override
public void onFinish() {
onZero();
zeroMillisAt = System.currentTimeMillis();
negativeTimer = new Timer();
negativeTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (cancelled) {
return;
}
onTickToc(zeroMillisAt - System.currentTimeMillis());
}
}, 0, countDownInterval);
}
};
return this;
}
public abstract void onTickToc(long millisFromFinished);
public abstract void onZero();
}
答案 1 :(得分:0)
声明
CountDownTimer cTimer = null;
long starttime = 0L;
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedtime = 0L;
int secs = 0;
int mins = 0;
Handler handler = new Handler();
可运行
public Runnable updateTimer = new Runnable() {
public void run() {
if (timeSwapBuff < 0) {
timeInMilliseconds = SystemClock.uptimeMillis() - starttime;
timeSwapBuff = timeSwapBuff - 1000;
secs = (int) (timeSwapBuff / 1000);
mins = secs / 60;
secs = -secs % 60;
} else {
timeInMilliseconds = SystemClock.uptimeMillis() - starttime;
updatedtime = timeSwapBuff + timeInMilliseconds;
secs = (int) (updatedtime / 1000);
mins = secs / 60;
secs = secs % 60;
}
tvEta.setText((timeSwapBuff < 0 ? "" : "-") + mins + ":" + String.format("%02d", secs));
handler.postDelayed(this, 1000);
}
};
//start timer method
void startTimer(long time) {
if (time < 0) {
timeSwapBuff = TimeUnit.SECONDS.toMillis(time);
handler.postDelayed(updateTimer, 0);
} else {
cTimer = new CountDownTimer(TimeUnit.SECONDS.toMillis(time), 100) {
public void onTick(long millisUntilFinished) {
long seconds = (millisUntilFinished / 1000) % 60;
int minutes = (int) (millisUntilFinished / (1000 * 60));
tvEta.setText(String.format("%d : %02d", minutes, seconds));
}
public void onFinish() {
starttime = SystemClock.uptimeMillis();
handler.postDelayed(updateTimer, 0);
}
};
cTimer.start();
}
}
//cancel timer
void cancelTimer() {
if (cTimer != null)
cTimer.cancel();
handler.removeCallbacks(updateTimer);
}