I have implemented the timer functionality in android app, I able to finish the timer from other local methods by calling timerObject.cancel()
. Its working perfectly.
But when I tried to call same in onTick()
method for specific condition, i am not able to cancel the timer, it last till the timer time ends.
How can i cancel the timer?
AFAIK You can not do that
But there is Drop-in alternative for the Android CountDownTimer class, but which you can cancel from within onTick.
Here you go
Looking at the source code for
CountDownTimer
it is easy to see why it is not working.cancel()
merely removes the message for ticking the timer from the queue. But the message handler that gets called at each tick posts a message for the next tick after callingonTick()
. So either you have to callcancel()
outside ofonTick()
, via aHandler
for example, or switch to using the Timer class instead.if using RXJava2. this code can help you.
using:
the owner of the code https://gist.github.com/chemickypes/fa3b7fc5b5a00a3ce37fee5815018702