javaandroidtimercountdowntimerandroid-timer

Delay For CountDown Timer - Android


I am making a chess clock but in it I need a delay (Like it waits 10 seconds before counting). I used a Handler for it but if the button is clicked in the 10 seconds, nothing happens. Please help! Thanks! My code:

    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);

I want a delay but I don't want to lock the UI and make the app unresponsive as it is doing right now with the handler. Any help will be appreciated! Thanks in advance!


Solution

  • I think you shouldn't put CountdownTimer into Handler. You could create 2 handler instead. Here is an example.

    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);
                }
    
            }
        });
    }