CountDownTimer.cancel() is not working in Android

前端 未结 2 478
悲&欢浪女
悲&欢浪女 2021-01-11 22:16

CountDownTimer.cancel() is not working in the below code:

myTimer = new CountDownTimer(10000, 1000) {
    public void onFinish() {
    }
    @Ov         


        
相关标签:
2条回答
  • 2021-01-11 22:31

    Solution By Gautier Hayoun :

    Just made a drop-in replacement for CountDownTimer that you can cancel from within onTick : Github link– Gautier Hayoun Dec 12 '10 at 1:04

    0 讨论(0)
  • 2021-01-11 22:42

    Instead of CountDownTimer use TimerTask

    final static long INTERVAL=1000;
    final static long TIMEOUT=10000;
    
    
    TimerTask task=new TimerTask(){
                @Override
                public void run() {
                    elapsed+=INTERVAL;
                    if(elapsed>=TIMEOUT){
                        this.cancel();
                        displayText("finished");
                        return;
                    }
                    //if(some other conditions)
                    //   this.cancel();
                    displayText("seconds elapsed: " + elapsed / 1000);
                }
            };
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(task, INTERVAL, INTERVAL);
    
    private void displayText(final String text){
        this.runOnUiThread(new Runnable(){
            @Override
            public void run() {
                mTextField.setText(text);
            }
        });
    }
    
    0 讨论(0)
提交回复
热议问题