asd
asd

Reputation: 21

How to make accurate timer on Android?

I have tried Handler, got no accuracy at all,

CountDownTimer, accurate most of time and

TimerTask, always accurate but on first call.

Scenario:

I'm trying to stop sound playing after specific amount of time.

Calling code

TimeTask task = new TimeTask();
Timer timer = new Timer();
task.setMediaPlayer(mediaPlayer);
timer.schedule(task, 400);
mediaPlayer.start();

I have created MediaPlayer that I'm giving to class that extends TimerTask. It will release MediaPlayer after specific amount of time.

class that extends TimerTask

private MediaPlayer mMediaPlayer = new MediaPlayer();

public void setMediaPlayer(MediaPlayer mediaPlayer) {
    this.mMediaPlayer = mediaPlayer;
    mMediaPlayer.start();
}

@Override
public void run() {
ListIterator<MediaPlayer> iterator = SoundboardMenu.mMediaPlayerList.listIterator();

        while (iterator.hasNext()) {
            MediaPlayer iteratedPlayer = iterator.next();
            if (iteratedPlayer.equals(mMediaPlayer)) {
                iteratedPlayer.release();
                iterator.remove();
                break;
            }
        }
}

It works fine but it's not always accurate enough.

If we wait over 5 seconds after calling class that extends TimerTask and call it again, then there will be slightly more delay and sound plays longer. If we call it repeatedly then we always get slightly shorter delay.

Upvotes: 0

Views: 3210

Answers (1)

hackbod
hackbod

Reputation: 91331

Handler is quite accurate, though it is dependent on the thread it is associated with actually running its message loop. If you are doing the Handler on your main thread, and your main thread goes out to lunch for 200ms... well, then of course the Handler can't fire during that time.

Of course, you don't say what you actually mean by "accurate" so it is hard to determine what you are expecting.

Upvotes: 2

Related Questions