Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

how to stop/cancel android CountDownTimer

I'm extending the CountDownTimer class to obtain some custom functionality .In onTick() in case some conditions are met I call cancel() , expecting that will be the end of it, however the onTick() callback gets call until the the count down is reached . So how to prevent this from happening ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

CountDownTimer.cancel() method seems to be not working. Here's another thread without a solution Timer does not stop in android.

I would recommend you to use Timer instead. It's much more flexible and can be cancelled at any time. It may be something like that:

public class MainActivity extends Activity {    
    TextView mTextField;
    long elapsed;
    final static long INTERVAL=1000;
    final static long TIMEOUT=5000;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mTextField=(TextView)findViewById(R.id.textview1);

        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);
            }});
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...