I am trying to run a CountDownTimer inside a Thread, but it just won't work..
So in the MainActivitys onCreate I start it on Button click like that:
public void onClick(final View v) {
Log.d("Main", "onClick");
runOnUiThread(runner);
}
runner
is an Instance of a class which implements Runnable
:
private CountDownLatch doneSignal = new CountDownLatch(1);
@Override
public void run() {
Log.d("WR", "run");
this.countDown(20);
Log.d("WR", "waiting");
try {
doneSignal.await();
} catch (final InterruptedException ex) {
Log.e("WR", ex.getMessage(), ex);
}
Log.d("WR", "waited");
}
private void countDown(int time) {
final CountDownTimer timer = new CountDownTimer(time * 1000, 1000) {
@Override
public void onTick(final long millisUntilFinished) {
Log.d("WR", "onTick");
}
@Override
public void onFinish() {
Log.d("WR", "onFinish");
doneSignal.countDown();
}
};
Log.d("WR", "starting");
timer.start();
Log.d("WR", "started");
}
With this code, the application just freezes after Logging onClick, run and starting.
Changing runOnUiThread(runner)
to new Thread(runner).start();
makes the application crash immediately after Logging onClick with no more output.
Some research said that the CountDownTimer needs to be run on UI-Thread due to the use of a Handler. But it just freezes.
When I remove the entire Thread stuff and just call runner.run();
in the Buttons onClick (also removing the implements Runnable in the runner Instance) I get following Log entries: onCLick, run, starting, started, waiting
. But then nothing happens, as if the timer does not run, no call of the onTick method.
How can I fix my CountDownTimer?