Android 倒数计时器不停止

Android Countdown Timmer does not stop

我是新手 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 秒


你基本上是这样做的:

String endTime = "22.05.2019, 23:48:00"; 
milliseconds = endDate.getTime(); // 1558565280
new CountdownTimer(milliseconds, 1000)

这将从一个非常大的数字开始倒计时:-)(1558565280 毫秒 == 432.93 小时)


也许你打算这样做:

countDownTimer = new CountDownTimer(diff, 1000)