Android CountDownTimer取消倒计时

时间:2015-07-24 11:00:49

标签: android countdowntimer

我在下面有类MainActivity,我需要从其他类取消onBackPressed方法的倒计时。我还复制了下面的CountDownTimer类。如何正确地完成任何帮助?谢谢你的回复。

 @Override
    public void onCreate(Bundle savedInstanceState) {


    textViewTime = (TextView) findViewById(R.id.tv_Time);
    textViewTime.setText(getString(R.string.countdown_time));

    final CounterClass timer = new CounterClass(10999, 900);
    timer.start();

    btnStop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            timer.cancel();
        }
    });
}

@Override
public void onBackPressed() {
    super.onBackPressed();

// here cancel // 

}

    public class CounterClass extends CountDownTimer {

    public CounterClass(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
    }

    @Override
    public void onFinish() {
        textViewTime.setText("COMPLETED");

    }

    @Override
    public void onTick(long millisUntilFinished) {
        long millis = millisUntilFinished;
        String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
                TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
                TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
        textViewTime.setText(hms);
    }
}

1 个答案:

答案 0 :(得分:1)

CountDownTimer有一个cancel()方法,可以调用它来终止计时器。

您的MainActivity看起来像这样

public class MainActivity extends Activity {

    private final CounterClass timer;

    @Override 
    public void onCreate() {
         timer = new CounterClass(10999, 900);
         timer.start();
         /* rest of the code omitted */
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        timer.cancel()
    }
}