2012-09-21 122 views
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我不知道爲什麼。

回答

2

不!您應該使用一個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秒