0
我需要一個倒數計時器,就像Android的CountDownTimer
一樣,除非我需要它在註冊時達到零,然後繼續到底片。有沒有一個優雅的解決方案呢?CountDownTimer繼續進入底片
我需要一個倒數計時器,就像Android的CountDownTimer
一樣,除非我需要它在註冊時達到零,然後繼續到底片。有沒有一個優雅的解決方案呢?CountDownTimer繼續進入底片
我找不到一個優雅的解決方案,所以我創建了一個。讓我知道是否有更好的東西已經存在,或任何改進,你可以做:
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();
}
宣言
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();
的Runnable
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);
}
太快速創建一個。 –