嗨,我正在做一个简单的倒计时计时器,我想在暂停后恢复它。对我来说非常重要的是我不会把我的倒计时计时器放到public void方法中。
mTextViewCountDown = findViewById(R.id.text_view_countdown);
mButtonStartPause = findViewById(R.id.button_start_pause);
mButtonStartPause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mTimerRunning) {
pauseTimer();
} else {
startTimer();
}
}
});
updateCountDownText();
mCountDownTimer = new CountDownTimer(mTimeLeftInMillis, 1000) {
@Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
@Override
public void onFinish() {
mTimerRunning = false;
}
}.start();
}
private void startTimer() {
mTimerRunning = true;
mCountDownTimer.start();
}
private void pauseTimer() {
mCountDownTimer.cancel();
mTimerRunning = false;
mButtonStartPause.setText("Start");
}
private void updateCountDownText() {
int minutes = (int) (mTimeLeftInMillis / 1000) / 60;
int seconds = (int) (mTimeLeftInMillis / 1000) % 60;
String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
mTextViewCountDown.setText(timeLeftFormatted);
}
1条答案
按热度按时间j1dl9f461#
是的,但是您需要创建计时器的新示例并传递当前暂停的时间
请阅读此处的详细信息:持续暂停/停止和启动/恢复java timertask?