Use CountDown Timer or Roll Your Own Based on Handler on Android

This post: http://android-developers.blogspot.co.uk/2007/11/stitch-in-time.html

describes how to implement a timer using a handler. I could achieve the same using the CountDown timer: http://developer.android.com/reference/android/os/CountDownTimer.html

This will work in the foreground service, which plays music in order to stop the music after a certain period of time (think of musical chairs). The timings should be reliable when the screen is locked, I think that its launch in the foreground should provide this, right?

I know from this post: Why does CountDown Timer in Android use a handler?

that the CountDown timer is implemented using a handler, so I think it probably doesn’t matter what I use, but before starting the coding, I thought I would look for the wisdom of the crowd!

Thanks Andrew

+4
source share
1 answer

I ended up working with a handler and it works great:

//required import
import android.os.Handler;

//class wide variable... are these considered bad? 
private Handler timeHandler = new Handler();

//wherever in your code you want to begin the timer or reset it
timeHandler.removeCallbacks(updateTime);
timeHandler.postDelayed(updateTime, 100);    

//this is the callback which will be called every 100ms or whatever value you gave in postDelayed

private Runnable updateTime = new Runnable() {
            public void run() {
                timeHandler.postDelayed(this, 100);
                currentTimeMillis = currentTimeMillis + 100;
                //do whatever you need to do every 100ms here... or whenever currentTimeMillis reaches the value you're waiting for.
        }

I added wakeLock so that the processor does not sleep if the screen is locked, and the front-end service is also used. It was exactly in the tests that I have done so far.

+3
source

All Articles