我怎么能停止计时器?

时间:2011-12-12 12:10:23

标签: java android timer

我有一个简单的问题,我怎么能停止计时器?

 Button bCancel = (Button)findViewById(R.id.bt1);
 bCancel.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            finish();
            startActivity(new Intent("com.jom.testcdt2.CANCELCLASS"));

        }
    });


    final Thread logoTimer = new Thread(){
        public void run(){
            try {
                int logoTimer = 0;
                while (logoTimer < 10000) {
                    sleep(100);
                    logoTimer = logoTimer + 100;

                }
                startActivity(new Intent("com.jom.testcdt2.CLEARSCREEN"));
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
            finally{
                finish();
            }
        }
    };
    logoTimer.start();    
} 

当我按下按钮bCancel时,它会启动一个新的活动,但是计时器仍然在运行,10秒后它会启动CLEARSCREEN。点击我希望计时器停止。我怎么能这样做?

2 个答案:

答案 0 :(得分:5)

我建议使用CountDownTimer

final CountDownTimer myTimer = new CountDownTimer(10000, 5000) {
@Override
public void onFinish() {
    //DO SOMETHING AFTER 10 000 ms
    }

    @Override
    public void onTick(long millisUntilFinished) {
    //DO SOMETHING EVERY 5 000 ms until stopped
    }
}
myTimer.start() //Starts it
myTimer.cancel() //Stops it

而不是写

(new Intent("com.jom.testcdt2.CANCELCLASS")

你应该使用

(new Intent(YOURCLASS.this, CancelClass.class)

答案 1 :(得分:3)

您是否可以尝试使用在while循环中检查的布尔值,并在按下取消按钮时将其设置为true?

boolean pressedCancel = false;
.... 

while (logoTimer < 10000 && !pressedCancel) {
    ....