CountDownTimer onfinish方法在更改活动后运行

时间:2016-05-25 11:14:56

标签: android

我在我的代码中使用CountDownTimer,当我运行应用程序时我有一个问题,即当我进入下一级别(转到下一个活动)时,计时器应该停止并且不要运行onfinish方法但是当第一级计时器停机时它运行onfinish方法并转到活动GameOver。

我使用Intent在我的活动和我的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();

对不起我的简单问题,感谢您的阅读。

4 个答案:

答案 0 :(得分:1)

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

//并在OnStop中

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

答案 1 :(得分:1)

你应该在开始下一级之前调用countDownTimer.cancel()。它将取消counDownTimer并且不会打电话给onFinish。

答案 2 :(得分:0)

public void onStop(){

   //Cancel your timer here before going to  next activity.

}

答案 3 :(得分:0)

CountDownTimer countDownTimer;

//in on Resume()

countDownTimer = new CountDownTimer(timeoflevel, 1000) {
    public void onTick(long millisUntilFinished) {
    txtclock2.setText("Time: " + millisUntilFinished / 1000);
        //TODO perform operation
    }
    public void onFinish() {
        txtclock2.setText("..Finish..");
        Intent intent = new Intent(Play.this , GameOver.class);
        startActivity(intent);
    }
}.start();

// Cancel Timer in onPause()

public void in onPause(){
    countDownTimer.cancel();
}