编程语言
首页 > 编程语言> > Java-倒数计时器延迟-Android

Java-倒数计时器延迟-Android

作者:互联网

我正在制作一个国际象棋时钟,但我需要延迟一下(例如,它需要等待10秒钟才能计数).我为此使用了处理程序,但是如果在10秒钟内单击按钮,则什么也没有发生.请帮忙!谢谢!
我的代码:

    mHandler.postDelayed(new Runnable() {
                        public void run() {
                            // count down timer start
                            timer2 = new CountDownTimer(totalSeconds, Integer.parseInt(delay.getText().toString())) {
                                public void onTick(long millisUntilFinished) {
                                    secondsTimer = (int) (millisUntilFinished / 1000) % 60;
                                    minutesTimer = (int) ((millisUntilFinished / (1000 * 60)) % 60);
                                    hoursTimer = (int) ((millisUntilFinished / (1000 * 60 * 60)) % 24);
                                    person2.setText(hoursTimer + ":" + minutesTimer + ":" + secondsTimer);
                                }

                                public void onFinish() {
                                    person2.setText("Time Up!");
                                    person2.setBackgroundColor(Color.RED);
                                    mp.start();
                                }
                            }.start();
                        }
                    }, finalDelay);

我需要一个延迟,但是我不想锁定UI并使应用程序无响应,因为它现在正在使用处理程序进行操作.任何帮助将不胜感激!提前致谢!

解决方法:

我认为您不应该将CountdownTimer放入Handler.您可以创建2个处理程序.这是一个例子.

private void startHandlerAndWait10Seconds(){
    Handler handler1 = new Handler();
    handler1.postDelayed(new Runnable() {

        public void run() {
            // Start Countdown timer after wait for 10 seconds
            startCountDown();

        }
    }, 10000);
}

private void startCountDown {
    final Handler handler2 = new Handler();
    handler2.post(new Runnable() {
        int seconds = 60;

        public void run() {
            seconds--;
            mhello.setText("" + seconds);
            if (seconds < 0) {
                // DO SOMETHING WHEN TIMES UP
                stopTimer = true;
            }
            if(stopTimer == false) {
                handler2.postDelayed(this, 1000);
            }

        }
    });
}

标签:android-timer,countdowntimer,timer,java,android
来源: https://codeday.me/bug/20191111/2022034.html