简体   繁体   中英

Class countdown timer doesn't reset

I have a class countdown timer that I want to reset but when it resets it wont start again. Basicaly when the counter gets to 0 (when the status is "done"), sets x = 1 and then in the activity checks if x = 1 , and then the counter resets. When the reset method from within the class is called it shows that it has reset but it wont start counting again

Timer class:

public class countdown_timer {
private long pls;
private long millisInFuture;
private long countDownInterval;
private boolean status;
int x = 0;
public countdown_timer(long pMillisInFuture, long pCountDownInterval) {
    this.millisInFuture = pMillisInFuture;
    this.countDownInterval = pCountDownInterval;
    this.pls = pMillisInFuture;
    status = false;
    Initialize();
}
    public void Stop() {
    status = false;
}
    public int GetNumberX() {
    return x;
}

public void Reset() {
    millisInFuture = pls;
    x=0;
}
    public void Start() {
    status = true;
}

public void Initialize() {
    final Handler handler = new Handler();
    Log.v("status", "starting");
    final Runnable counter = new Runnable() {

        public void run() {
            long sec = millisInFuture / 1000;
            if (status) {
                if (millisInFuture <= 0) {
                    Log.v("status", "done");
                    x = 1;
                } else {
                    Log.v("status", Long.toString(sec) + " seconds remain");
                    millisInFuture -= countDownInterval;
                    handler.postDelayed(this, countDownInterval);
                }
            } else {
                Log.v("status", Long.toString(sec) + " seconds remain and timer has stopped!");
                handler.postDelayed(this, countDownInterval);
            }
        }
    };

    handler.postDelayed(counter, countDownInterval);
}

Activity that uses the timer class:

mycounterup = new countdown_timer(startcard, 1000);
xup = mycounterup.GetNumberX();
if (xup == 1) {
   mycounterup.Reset();
   mycounterup.Start();

Thanks for any help.

try changing your start method as and one thing more i don't know if its a typo or what change mycounter.Start(); to mycounterup.Start();

 public void Start() {
 status = true;
 Initialize();
}

save the counter state so that next time if you have to pause or resume the thing you are able to do it also

You should change your Reset method:

public void Reset() {
    millisInFuture = pls;
    x=0;
    Initialize();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM