Wednesday, May 9, 2012

Your own CountDownTimer in Android


Android CountDownTimer sucks. Why ? because in CountDownTimer.java (Android source code) it creates a mHandler inside the code which requires to call Looper.prepare() and Looper.loop() before calling new CountDownTimer(), You are likely to get Can't create handler inside thread that has not called Looper.prepare() because of this.

  So I wrote my own version of  CountDownTimer using Thread.

Here is it.


abstract class CountDownTimer extends Thread {
    public abstract void onFinish();
    private boolean mCancelled = false;
 
    public void run() {
    mCancelled = false;
    start(60);
    }
 
    private final void start(long secs) {
    long delay = secs * 1000;
do {
delay = delay - 1000;
try {
Thread.sleep(1000);
} catch (InterruptedException e) { }
if(mCancelled) {
return;
}
} while (delay > 0);
onFinish();
    }
        public final void cancel() {
    mCancelled = true;
    }
}

How to use
=========


CountDownTimer countDownTimer = new CountDownTimer()  {
@Override
public void onFinish() {

}
};

countDownTimer.start();




1 comment: