Countdown timer with pause and resume

后端 未结 8 951
小蘑菇
小蘑菇 2021-01-05 04:17

I want to do countdown timer with pause and restart.Now i am displaying countdown timer By implenting ontick() and onfinish().please help me out.HEre is th code for countdow

8条回答
  •  轮回少年
    2021-01-05 04:28

    A nice and simple way to create a Pause/Resume for your CountDownTimer is to create a separate method for your timer start, pause and resume as follows:

    public void timerStart(long timeLengthMilli) {
            timer = new CountDownTimer(timeLengthMilli, 1000) {
    
                @Override
                public void onTick(long milliTillFinish) {
                    milliLeft=milliTillFinish;
                    min = (milliTillFinish/(1000*60));
                    sec = ((milliTillFinish/1000)-min*60);
                    clock.setText(Long.toString(min)+":"+Long.toString(sec));
                    Log.i("Tick", "Tock");
                }
    

    The timerStart has a long parameter as it will be reused by the resume() method below. Remember to store your milliTillFinished (above as milliLeft) so that you may send it through in your resume() method. Pause and resume methods below respectively:

    public void timerPause() {
            timer.cancel();
        }
    
        private void timerResume() {
            Log.i("min", Long.toString(min));
            Log.i("Sec", Long.toString(sec));
            timerStart(milliLeft);
        }
    

    Here is the code for the button FYI:

    startPause.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(startPause.getText().equals("Start")){
                        Log.i("Started", startPause.getText().toString());
                        startPause.setText("Pause");
                        timerStart(15*1000);
                    } else if (startPause.getText().equals("Pause")){
                        Log.i("Paused", startPause.getText().toString());
                        startPause.setText("Resume");
                        timerPause();
                    } else if (startPause.getText().equals("Resume")){
                        startPause.setText("Pause");
                        timerResume();
                    }
    

提交回复
热议问题