0

我正在尝试每两秒播放一次通知声音。我的代码如下:

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 。

4

1 回答 1

2

不!您应该使用 aTimer来执行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 秒

于 2012-09-21T20:30:21.620 回答