Android: CountDownTimer skips last onTick()!

前端 未结 12 670
眼角桃花
眼角桃花 2020-11-27 14:51

Code:

public class SMH extends Activity {  

    public void onCreate(Bundle b) {  
        super.onCreate(b);  
        setContentView(R.layou         


        
12条回答
  •  遥遥无期
    2020-11-27 15:16

    So I think I went a little over board because my timer runs in its own thread instead of using postDelay handlers, though it always posts back to the thread it was created in. I also knew that I only cared about seconds so its simplified around that idea. It also lets you cancel it and restart it. I do not have pausing built in because that's not in my needs.

    /**
    * Created by MinceMan on 8/2/2014.
    */
    public abstract class SecondCountDownTimer {
    
    private final int seconds;
    private TimerThread timer;
    private final Handler handler;
    
    /**
     * @param secondsToCountDown Total time in seconds you wish this timer to count down.
     */
    public SecondCountDownTimer(int secondsToCountDown) {
        seconds = secondsToCountDown;
        handler = new Handler();
        timer = new TimerThread(secondsToCountDown);
    }
    
    /** This will cancel your current timer and start a new one.
     *  This call will override your timer duration only one time. **/
    public SecondCountDownTimer start(int secondsToCountDown) {
        if (timer.getState() != State.NEW) {
            timer.interrupt();
            timer = new TimerThread(secondsToCountDown);
        }
        timer.start();
        return this;
    }
    
    /** This will cancel your current timer and start a new one. **/
    public SecondCountDownTimer start() {
        return start(seconds);
    }
    
    public void cancel() {
        if (timer.isAlive()) timer.interrupt();
        timer = new TimerThread(seconds);
    }
    
    public abstract void onTick(int secondsUntilFinished);
    private Runnable getOnTickRunnable(final int second) {
        return new Runnable() {
            @Override
            public void run() {
                onTick(second);
            }
        };
    }
    
    public abstract void onFinish();
    private Runnable getFinishedRunnable() {
        return new Runnable() {
            @Override
            public void run() {
                onFinish();
            }
        };
    }
    
    private class TimerThread extends Thread {
    
        private int count;
    
        private TimerThread(int count) {
            this.count = count;
        }
    
        @Override
        public void run() {
            try {
                while (count != 0) {
                    handler.post(getOnTickRunnable(count--));
                    sleep(1000);
                }
            } catch (InterruptedException e) { }
            if (!isInterrupted()) {
                handler.post(getFinishedRunnable());
            }
        }
    }
    

    }

提交回复
热议问题