检查 CountDownTimer 是否正在运行

问题描述 投票:0回答:4

我一直在寻找一种方法来查看 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 当前是否正在运行?

android timer countdowntimer
4个回答
58
投票

只需放置一个

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

3
投票

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

0
投票

mCountDown = null
中设置
onFinish()
将保存一个标志。为了检查它是否正在运行
if (mCountDown != null)

© www.soinside.com 2019 - 2024. All rights reserved.