我试图每两秒播放一次通知声音。我的代码如下:
final Handler myHandler = new Handler();
mMediaPlayer = new MediaPlayer();
final Runnable mMyRunnable = new Runnable()
{
@Override
public void run()
{
try
{
mMediaPlayer.setDataSource(getBaseContext(), getAlarmUri(alarm_number));
final AudioManager audioManager = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0)
{
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
}
catch (IOException e)
{
}
}
};
mMediaPlayer.setOnCompletionListener(new OnCompletionListener()
{
@Override
public void onCompletion(MediaPlayer mp)
{
myHandler.postDelayed(mMyRunnable, 2000);
}
});
myHandler.post(mMyRunnable);
当代码执行时,通知声音播放一次,然后我在行mMediaPlayer.setDataSource(...
处收到IllegalStateException
我不明白为什么。
答案 0 :(得分:2)
NO!您应该使用Timer
执行TimerTask
以获得您选择的重复率:
Timer timer = new Timer();
TimerTask task = new TimerTask()
{
@Override
public void run()
{
// Do your work here
}
};
timer.schedule(task, 'DELAY_FOR_EXECUTION', 'TIME_TO_WAIT');
example:
`//timer.schedule(task, 0, 5000);`
这将立即运行,每5秒