as seen in Sam's post on here, I am unsure what method to use to start the countdown timer "AccurateCountDownTimer".
It will be called from a button (onClick) which is easily set up later. And the Time remaining will be displayed on a text view.
Here is my code:
public abstract class AccurateCountDownTimer {
public AccurateCountDownTimer(long millisInFuture, long countDownInterval) {
long seconds = (millisInFuture / 1000);
mMillisInFuture = millisInFuture;
mCountdownInterval = countDownInterval;
// ************AccurateCountdownTimer***************
mTickCounter = 0;
// ************AccurateCountdownTimer***************
testTimer.setText(String.format("%02d", seconds / 60) + ":"
+ String.format("%02d", seconds % 60));
}
/**
* Cancel the countdown.
*/
public final void cancel() {
mHandler.removeMessages(MSG);
}
/**
* Start the countdown.
*/
public synchronized final AccurateCountDownTimer start() {
if (mMillisInFuture <= 0) {
onFinish();
return this;
}
mNextTime = SystemClock.uptimeMillis();
mStopTimeInFuture = mNextTime + mMillisInFuture;
mNextTime += mCountdownInterval;
mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG), mNextTime);
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 (AccurateCountDownTimer.this) {
final long millisLeft = mStopTimeInFuture - SystemClock.uptimeMillis();
if (millisLeft <= 0) {
onFinish();
} else {
onTick(millisLeft);
// Calculate next tick by adding the countdown interval from the original start time
// If user's onTick() took too long, skip the intervals that were already missed
long currentTime = SystemClock.uptimeMillis();
do {
mNextTime += mCountdownInterval;
} while (currentTime > mNextTime);
// Make sure this interval doesn't exceed the stop time
if(mNextTime < mStopTimeInFuture)
sendMessageAtTime(obtainMessage(MSG), mNextTime);
else
sendMessageAtTime(obtainMessage(MSG), mStopTimeInFuture);
}
}
}
};
}