取消并重新启动CountDownTimer问题

时间:2011-03-28 03:59:36

标签: java android

嗨,我遇到了CountDownTimer函数的问题

首先我可以使用counter.cancel()来停止倒计时; 然后我将milliUntilFinished值存储在countercur中。

然后我使用存储的countercur值重新启动计时器。 一切正常。但是当我试图取消第二次时,它再也不会停止计时器了。 只运作一次,我错过了什么?这是我的代码谢谢:

// Main code :
MyCount counter = new MyCount(59000, 1000);
            counter.start(); // start timer at 59 seconds

///

button1.setOnClickListener(new View.OnClickListener() { 


    public void onClick(View v) {
counter.cancel(); // -- > cancelling the timer works here, the clock stops ok
//
// rest of code snipped

button2.setOnClickListener(new View.OnClickListener() { 
       public void onClick(View v) {
      MyCount counter= new MyCount(countcur,1000); // countcur is the current counter value when last cancelled

           counter.start(); // This restarts timer ok. when when retrying button 1 to cancel again, it never cancels.

// rest of code snipped

// Timer Setup
    public class MyCount extends CountDownTimer {

        public MyCount(long millisInFuture, long countDownInterval) {

        super(millisInFuture, countDownInterval);
        }    
        public void onFinish() {
Intent intent = new Intent(); 
            intent.setClass(Main.this, Final.class);
            startActivity(intent);
            }
            else {
            MyCount counter = new MyCount(59000, 1000);
            counter.start();
            clock = counter.toString();
            }

        }    
        public void onTick(long millisUntilFinished) {
            //int min = 5;
            /*if (+millisUntilFinished / 1000 <= 240) {
                min = 4;
                mintosec = "240";

                //millisUntilFinished = 59000;
            }
            else if (+millisUntilFinished / 1000 <= 180) {
                min = 3;
                mintosec = "180"; }
            else if (+millisUntilFinished / 1000 <= 120) {
                min = 2;
                mintosec = "120"; }
            else if (+millisUntilFinished / 1000 <= 60)
                min =1;
                mintosec = "60"; */

            //TextView totmin = (TextView) findViewById(R.id.clockmin);
            //totmin.setText("");
            TextView totsec = (TextView) findViewById(R.id.clocksec);
            totsec.setText(+duration +" : "+ millisUntilFinished / 1000);
            countcur = millisUntilFinished; // store current count value for pausing and restarting
        }
    }  // End Timer

1 个答案:

答案 0 :(得分:3)

在下文中,您将设置局部变量而不是类变量:

button2.setOnClickListener(new View.OnClickListener() { 
       public void onClick(View v) {
      MyCount counter= new MyCount(countcur,1000); // countcur is the current counter value when last cancelled

将其更改为引用现有的类变量:

button2.setOnClickListener(new View.OnClickListener() { 
       public void onClick(View v) {
     counter= new MyCount(countcur,1000); // countcur is the current counter value when last cancelled