2014-01-30 250 views
8

我一直都盼望看到的方法,看是否有CountDownTimer运行与否,但我不能找到一个办法,任何帮助将不胜感激检查是否CountDownTimer运行

if (position == 0) { 

    mCountDown = new CountDownTimer((300 * 1000), 1000) { 

     public void onTick(long millisUntilFinished) { 
      mTextField.setText("seconds remaining: " 
        + millisUntilFinished/1000); 
     } 

     public void onFinish() { 
      mTextField.setText("0:00"); 
      String path = "/sdcard/Music/ZenPing.mp3"; 
      try { 

       mp.reset(); 
       mp.setDataSource(path); 
       mp.prepare(); 
       mp.start(); 

      } catch (IOException e) { 
       Log.v(getString(R.string.app_name), 
         e.getMessage()); 
      } 
     } 
    }.start(); 

} 

对于如何能我检查mCountDown是否正在运行?

+0

难道你不能使用全局布尔值吗?在调用新的CountDownTimer时将in设置为TRUE并将onFinish()设置为FALSE? –

+0

你能详细说说你想达到什么吗? – MGDroid

+1

请注意,在onTick()和onFinish()方法中使用布尔变量来指示定时器的状态并不明确。您可以通过cancel()方法停止定时器。在这种情况下,您的变量将仍然为真,并指示错误的状态。 –

回答

29

只要把boolean标志,它表明,通过下面的代码

boolean isRunning = false; 

mCountDown = new CountDownTimer((300 * 1000), 1000) { 

    public void onTick(long millisUntilFinished) { 
     isRunning = true; 
     //rest of code 
    } 

    public void onFinish() { 
     isRunning= false; 
     //rest of code 
    } 
}.start(); 
1

onTick是您正在运行的进程的回调,您可以设置属性来跟踪状态。

isTimerRunning =false; 

start -> make it true;OnTick -> make it true(实际上不是必需的,但仔细检查) 内OnFinish -> make it false;

使用isTimerRunning属性来跟踪状态。

0

检查是否CountDownTimer正在运行并且如果应用程序在后台运行。

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    ... 
    myButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      myButton.setText("Button clicked"); 
      countDownTimer = new CountDownTimer(3000, 1000) { 
       @Override 
       public void onTick(long millisUntilFinished) { 
        //After turning the Smartphone the follow both methods do not work anymore 
        if (!runningBackground) { 
         myButton.setText("Calc: " + millisUntilFinished/1000); 
         myTextView.setText("Calc: " + millisUntilFinished/1000); 
        } 
       } 
       @Override 
       public void onFinish() { 
        if (!runningBackground) { 
         //Do something 
        } 
        mTextMessage.setText("DONE"); 
        runningBackground = false; 
        running = false; 
       } 
      }; 
      //timer started 
      countDownTimer.start(); 
      running = true; 
     } 
    }); 
} 

@Override 
protected void onResume() { 
    super.onResume(); 
    runningBackground = false; 
} 

@Override 
protected void onPause() { 
    runningBackground = true; 
    super.onPause(); 
}