Reputation: 7927
I am attempting to play a notification sound once every two seconds. My code is as follows:
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);
When the code executes, the notification sound plays once and then I get an IllegalStateException at the line mMediaPlayer.setDataSource(...
I have no idea why.
Upvotes: 0
Views: 1374
Reputation: 536
NO! You should use a Timer
which will execute a TimerTask
for a repeat rate that you choose:
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);`
This will run immediatly, every 5 secs
Upvotes: 2