Countdown timer with pause and resume

后端 未结 8 908
小蘑菇
小蘑菇 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:32

    //This timer will show min:sec format and can be paused and resumed
    
    public class YourClass extends Activity{
    TextView timer;
    CountDownTimer ct;
    long c = 150000; // 2min:30sec Timer
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
    
        setContentView(R.layout.YourXmlLayout);
        timer = (TextView)findViewById(R.id.Yourtimer)
        startTimer(); // it will start the timer
    
    }
    
    public void startTimer(){
    ct = new CountDownTimer(c,1000) {
        @Override
        public void onTick(long millisUntilFinished) {
        // Code to show the timer in min:sec form
        // Here timer is a TextView so
        timer.setText(""+String.format("%02d:%02d",millisUntilFinished/60000,(millisUntilFinished/1000)%60));
        c = millisUntilFinished; // it will store millisLeft
        }
    
        @Override
        public void onFinish() {
            //your code here
    
        }
    };
    ct.start();
    
    }
    /*===========================================================
    *after creating this you can pause this by typing ct.cancel()
    *and resume by typing startTimer()*/
    

提交回复
热议问题