检查CountDownTimer是否正在运行

时间:2014-01-30 08:38:35

标签: android timer 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当前是否正在运行?

3 个答案:

答案 0 :(得分:40)

只需输入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 :(得分:1)

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

isTimerRunning =false;

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

使用isTimerRunning属性来跟踪状态。

答案 2 :(得分: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();
}