播放声音在固定的时间间隔最好的方式? [英] Best way to play sound on a timed interval?
问题描述
我有一个Android应用程序,需要播放声音的资源在固定的时间间隔,例如每120秒。
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?
推荐答案
我结束了开沟定时
方法,并使用了处理程序
位于在一个例子绊脚石后,而不是Android的实验室。
I ended up ditching the Timer
approach and used a Handler
instead after stumbling upon an example at android-labs.
因此,而不是产卵定时
和的TimerTask
在我的活动的的onCreate
,我宣布本次非公开处理程序
与行的Runnable
:
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()));
}
};
另外,我不得不code添加到我的活动的 onResume
和的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.
这篇关于播放声音在固定的时间间隔最好的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!