我正在使用此Android类来实现倒计时:http://developer.android.com/reference/android/os/CountDownTimer.html
我创建了一个自己的类My Count:
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
tv_test.setText("");
}
@Override
public void onTick(long millisUntilFinished) {
tv_test.setText("d"+ (millisUntilFinished/(3600000*24))+ " h: "+ (millisUntilFinished/3600000)%24 +" m: " + (millisUntilFinished/60000) % 60 + " sec: "+ (millisUntilFinished/1000) % 60);
}
}
在我的活动的onStart()中我有这段代码:
MyCount counter = new MyCount(time, 1000);
counter.start();
现在的问题是:如果我导航到下一个活动并返回,则会再次启动倒数计时器并进行两次倒计时。
我无法将其放在onCreate()中,因为用户可以更改时间变量。他在另一项活动中改变了它
答案 0 :(得分:1)
尝试添加布尔值 例如:
booelan counterIsLaunched = false;
boolean timeChanged = false;
并在您的计数器实现中添加:
@Override
public void onFinish() { tv_test.setText("");
counterIsLaunched = false;
if(timeChanged) start();
}
@Override
public void onTick(long millisUntilFinished) {
tv_test.setText("d"+ (millisUntilFinished/(3600000*24))+ " h: "+ (millisUntilFinished/3600000)%24 +" m: " + (millisUntilFinished/60000) % 60 + " sec: "+ (millisUntilFinished/1000) % 60);
counterIsLaunched = true;
if(timeChanged) start();
}
并在你的onStart()中尝试测试变量
if(counter.getCounterIsLaunched() == false ) {
counter.start();
}
当您更改计时器时,请执行以下操作:
counter.getTimeChanged() = true;
希望它有助于男人:)