user1977132
user1977132

Reputation: 497

Use CountDown Timer or roll my own based on Handler in 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 thing using a CountDown timer: http://developer.android.com/reference/android/os/CountDownTimer.html

This will be running in a foreground service which is playing music in order to stop the music after a specified period of time (think musical chairs). The timings need to be reliable when the screen is locked, I think running it in a foreground service should ensure this, is this the case?

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

that CountDown timer is implemented using a handler so my thinking is that it probably doesn't matter which I use but before I start coding I thought I would seek the wisdom of the crowd!

Thanks, Andrew

Upvotes: 4

Views: 1694

Answers (1)

user1977132
user1977132

Reputation: 497

I ended up going for a Handler and it is working fine:

//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 a wakeLock to keep the CPU awake if the screen is locked and also used a foreground service. It's been accurate in the tests I've done so far.

Upvotes: 3

Related Questions