gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:38:45 24 4
gpt4 key购买 nike

我的游戏 Activity 中有一个倒计时器,当我接到来电或某些 Activity 失去焦点时,我需要暂停它。我尝试这样做,但它不起作用(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();
}

最佳答案

我认为您不需要扩展它,除非确实有必要。我赞同 codeMagic 所说的 - 将剩余时间存储在 onPause() 中的变量中,并且不要忘记将其保存在 onSaveInstanceState() 中或到SharedPreference

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

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

关于java - 如何暂停和恢复倒计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25330265/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com