ali khorshidi rozbahani ali khorshidi rozbahani - 6 months ago 42
Android Question

CountDownTimer onfinish method run after change activity

I use CountDownTimer in my code and when i run app i have one problem that is when i go to next level ( go to next activity ) the timer should be stop and dont run the onfinish method but when the first level timer down it run the onfinish method and go to activity GameOver .

I use Intent to move between my activity and my CountDownTimer is :

new CountDownTimer(timeoflevel, 1000) {

public void onTick(long millisUntilFinished) {
txtclock2.setText("Time: " + millisUntilFinished / 1000);
//here you can have your logic to set text to edittext
}

public void onFinish() {

txtclock2.setText("..Finish..");
Intent intent = new Intent(Play.this , GameOver.class);
startActivity(intent);
}

}.start();


Sorry for my easy question and thanks for reading .

Answer
CountDownTimer countDownTimer;



countDownTimer = new CountDownTimer(timeoflevel, 1000) {
        public void onTick(long millisUntilFinished) {
            txtclock2.setText("Time: " + millisUntilFinished / 1000);
            //here you can have your logic to set text to edittext
        }

        public void onFinish() {

            txtclock2.setText("..Finish..");
            Intent intent = new Intent(Play.this , GameOver.class);
        startActivity(intent);
    }
}.start();


and in OnStop 

public void onStop(){
       countDownTimer.cancel();

}