Pause CountDownTimer in Android when activity is not in front

后端 未结 7 565
旧巷少年郎
旧巷少年郎 2020-12-02 20:43

I have an activity that uses a CountDownTimer that counts down from 10. How do I pause that timer when the activity is no longer in focus, like if the user get a call or som

相关标签:
7条回答
  • 2020-12-02 21:26

    No need to create a new Timer, just set the millisUntilFinished = total. For instance

    private CountDownTimer cdTimer;
    private long total = 30000;
    
            ...
            toggleButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view){
                    if(toggleButton.isChecked()) {
                        startCountDownTimer();
                    }else{
                        cdTimer.cancel();
                    }
                }
            });
            ...
    
        private void startCountDownTimer() {
            cdTimer = new CountDownTimer(total, 1000) {
                public void onTick(long millisUntilFinished) {
                    //update total with the remaining time left
                    total = millisUntilFinished;
                    nTimeLabel.setText("seconds remaining: " +  millisUntilFinished/ 1000);
                }
                public void onFinish() {
                    nTimeLabel.setText("done!");
                }
            }.start();
        }
    
    0 讨论(0)
提交回复
热议问题