views:

42

answers:

1

I have an Android app which needs to play a sound resource on a timed interval, say every 120 seconds.

I know how to access the sound resources and play them, however it's time timer part I'm not sure of. What's the best approach?

A: 

I ended up ditching the Timer approach and used a Handler instead after stumbling upon an example at android-labs.

So, instead of spawning the Timer and TimerTask in my Activity's onCreate, I declared this private Handler with in-line Runnable:

private Handler _playRandomSoundHandler = new Handler();
private Runnable _playRandomSoundTask = new Runnable() {
    public void run() {
        SoundManager.playRandom();
        _playRandomSoundHandler.postDelayed(_playRandomSoundTask, Prefs.getDelayInMilliseconds(getApplicationContext()));
    }
};

Also, I had to add code to my Activity's onResume and onPause:

@Override
protected void onResume() {
    super.onResume();
    _playRandomSoundHandler.postDelayed(_playRandomSoundTask, Prefs.getDelayInMilliseconds(this));
}

@Override
protected void onPause() {
    super.onPause();
    _playRandomSoundHandler.removeCallbacks(_playRandomSoundTask);
    SoundManager.stop();
}

This approach seems to work great.

Edward J. Stembler