Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I stop a Timer?

I have a simple question, how can I stop 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();    
} 

When I press button bCancel, it starts a new activity, but timer is still running and after 10 seconds it starts CLEARSCREEN. On click I want timer to stop. How can I do that?

like image 654
JanOlMajti Avatar asked Mar 08 '26 23:03

JanOlMajti


1 Answers

I would recommend using a 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

And instead of writing

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

you should use

(new Intent(YOURCLASS.this, CancelClass.class)
like image 125
Force Avatar answered Mar 10 '26 12:03

Force