如何暂停和恢复倒数计时器?

时间:2014-08-15 16:25:12

标签: java android

我的游戏活动中有一个倒数计时器,当我接到来电或者我的活动失去焦点时,我需要暂停。我试过这样但它不起作用(onPause方法有效,它会停止计时器,但它不会恢复它):

private long total = 180000;

MyCount brojacVremena = new MyCount(total, 1000);

public class MyCount extends CountDownTimer {

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

        @Override
        public void onFinish() {


        @Override
        public void onTick(long millisUntilFinished) {
            total = millisUntilFinished;
            vreme.setText("" + millisUntilFinished / 1000);

        }
        }

@Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        MyCount brojacVremena = new MyCount(total, 1000);
        brojacVremena.start();
    }

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    brojacVremena.cancel();
}

我在onPause中尝试了这个:

@Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        MyCount brojacVremenaNew = new MyCount(total, 1000);
        brojacVremenaNew.cancel();
}

1 个答案:

答案 0 :(得分:1)

除非真的有必要,否则我认为你不需要扩展它。我的第二个代码是魔术师所说的 - 存储时间时间留在onPause()中的变量中,而不要忘记将其保存在onSaveInstanceState()SharedPreference中。

当您的活动恢复时,无论是由于配置更改还是其他原因,您都可以重新创建计时器:

new CountDownTimer(millisUntilFinished, tickTime) {

     public void onTick(long millisUntilFinished) {
         millisUntilFinished -= tickTime;
         // do you wanna know for whom the bell tolls?
     }

     public void onFinish() {
         // it tolls for thee
         millisUntilFinished = 0;
     }
  }.start();  

onPause()中,取消此计时器并在onResume()中根据剩余时间创建一个新的计时器实例:)

修改 像这样:

@Override
public void onResume(){
    super.onResume();
    millisUntilFinished = getMillisFromSharedPreference(KEY);
    if(millisUntilFinished != 0){
        new CountDownTimer(millisUntilFinished, tickTime) {

         public void onTick(long millisUntilFinished) {
             millisUntilFinished -= tickTime;
             // do you wanna know for whom the bell tolls?
         }

         public void onFinish() {
             // it tolls for thee
             millisUntilFinished = 0;
         }
        }.start();
    }
}

@Override
public void onPause(){
    super.onPause();
    saveMillisToSharedPreference(KEY,millisUntilFinished);
}