Countdown timer with pause and resume

后端 未结 8 980
小蘑菇
小蘑菇 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条回答
  •  猫巷女王i
    2021-01-05 04:43

    I am afraid that it is not possible to pause or stop CountDownTimer and pausing or stopping in onTick has no effect whatsoever user TimerTask instead.

    Set up the TimerTask

    class UpdateTimeTask extends TimerTask {
       public void run() {
           long millis = System.currentTimeMillis() - startTime;
           int seconds = (int) (millis / 1000);
           int minutes = seconds / 60;
           seconds     = seconds % 60;
    
           timeLabel.setText(String.format("%d:%02d", minutes, seconds));
       }
    
    }
    if(startTime == 0L) {
       startTime = evt.getWhen();
       timer = new Timer();
       timer.schedule(new UpdateTimeTask(), 100, 200);
    }
    

    You can add event listener's like this..

    private Handler mHandler = new Handler();
    
    ...
    
    OnClickListener mStartListener = new OnClickListener() {
       public void onClick(View v) {
           if (mStartTime == 0L) {
                mStartTime = System.currentTimeMillis();
                mHandler.removeCallbacks(mUpdateTimeTask);
                mHandler.postDelayed(mUpdateTimeTask, 100);
           }
       }
    };
    
    OnClickListener mStopListener = new OnClickListener() {
       public void onClick(View v) {
           mHandler.removeCallbacks(mUpdateTimeTask);
       }
    };
    

    For more refer to Android Documentation.

提交回复
热议问题