我是Android新手,我需要一些帮助。我正在使用倒数计时器来更新文本视图,直到某个日期。它的工作正常,但微调器不会在0:0:0:0处停止,而是继续运行,因为此0:0:0:-12。
我希望文本视图文本更改为从0:0:0:0开始。
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm:ss");
formatter.setLenient(false);
String endTime = "22.05.2019, 23:48:00";
Date endDate;
try {
endDate = formatter.parse(endTime);
milliseconds = endDate.getTime();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startTime = System.currentTimeMillis();
diff = milliseconds - startTime;
countDownTimer = new CountDownTimer(milliseconds, 1000) {
@Override
public void onTick(long millisUntilFinished) {
startTime = startTime - 1;
Long serverUptimeSeconds =
(millisUntilFinished - startTime) / 1000;
Toast.makeText(MainActivity.this, "Time left :" + serverUptimeSeconds, Toast.LENGTH_SHORT).show();
String daysLeft = String.format("%2d", serverUptimeSeconds / 86400);
String hoursLeft = String.format("%2d", (serverUptimeSeconds % 86400) / 3600);
String minutesLeft = String.format("%2d", ((serverUptimeSeconds % 86400) % 3600) / 60);
String secondsLeft = String.format("%2d", ((serverUptimeSeconds % 86400) % 3600) % 60);
countdownTimerText.setText(daysLeft + ":" + hoursLeft + ":" + minutesLeft + ":" + secondsLeft);
}
@Override
public void onFinish() {
countdownTimerText.setText("Start");
}
}.start();
CountdownTimers API需要millisInTheFuture
和interval
https://developer.android.com/reference/android/os/CountDownTimer.html#CountDownTimer(long,%20long)
更容易做类似的事情
new CountdownTimer(TimeUnit.Seconds.toMillis(30), TimeUnit.Seconds.toMillis(1))
// ^这将以1秒的间隔倒计时30秒