CountDownTimer即使app在Android中关闭也要运行

时间:2017-05-14 10:05:25

标签: android

new CountDownTimer(30000, 1000) {

     public void onTick(long millisUntilFinished) {
         mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
     }

     public void onFinish() {
         mTextField.setText("done!");
     }
  }.start();

1 个答案:

答案 0 :(得分:-1)

在活动的onDestroy()中停止计时器

CountDownTimer waitTimer;  //declare globally

waitTimer = new CountDownTimer(30000, 1000) {

 public void onTick(long millisUntilFinished) {
     mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
 }

 public void onFinish() {
     mTextField.setText("done!");
 }
}.start();

现在使用waitTimer.cancel();取消定时器

 public void onDestroy(){
    super.onDestroy();
    if(waitTimer != null) {
         waitTimer.cancel();
         waitTimer = null;
     }
}