问题
I was playing around with the CountDownTimer on Android and I came into sort of a dilemma. In my code, I have the following:
public class mCountDownTimer extends CountDownTimer{
protected boolean hasFinished = false;
public mCountDownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
public void onFinish(){
hasFinished = true;
}
@Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
}
}
Basically I want to find out if my CountDownTimer has finished. But in the function I want to call it in, I have some code that goes:
public void function(){
public boolean finished = false;
if(interrupted)
countDownTimer.cancel();
if(temporaryCountHolder == false){
countDownTimer.start();
interrupted = true;
}
}
How can i tell whether or not my timer has finished? I want to implement something that says:
if(countDownTimer.hasFinished == true){
Time now = new Time(); //finds the current time
now.setToNow();
String lsNow = now.format("%m-%d-%Y %I:%M:%S");
lsNow += " just Started\n";
try {
dumpToFile("StepsChanged", lsNow);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
But if I put the statement right after
if(temporaryCountHolder == false)
statement, then the if statement with hasFinished will always evaluate to be false. How can I get it so that I can record the time if and only if the timer has finished?
回答1:
As per your comments, the reason why you are getting the false value is because you are executing the statements before the timer has stopped.
You can go like below,
@Override
public void onFinish(){
hasFinished = true;
Time now = new Time(); //finds the current time
now.setToNow();
String lsNow = now.format("%m-%d-%Y %I:%M:%S");
lsNow += " just Started\n";
try {
dumpToFile("StepsChanged", lsNow);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
To simply record the time you can just move those methods to the onFinish method of countdowntimer class. I don't know about dumpToFile
if it is a method of another class you can make it a static method and use it or even some suitable alternative methods. Hope this helps.
回答2:
you need to cancel CountDownTimer in OnFinsh
@Override
public void onFinish() {
Log.v(TAG, "On Finish");
Intent intent = new Intent(TIME_OUT);
intent.putExtra("dialog", "timeout");
sendBroadcast(intent);
countDownTimer.cancel();
}
来源:https://stackoverflow.com/questions/15941935/find-if-countdowntimer-is-finished