2013-05-13 78 views
0

我想實現一種我們可以在汽車上找到的雷達來幫助停車。在通過活頁夾正確連接到我的活動的服務上,我啓動了一個線程,該線程必須重複一段短的sound.wav(長度爲110ms),並且短時間內會發生變化。 使用此代碼,開始時第一個循環播放聲音,但遇到困難並很快失去節奏。最糟糕的是,這項服務永遠不會停止。垃圾收集器已飽和。 我沒有找到正確實現這一點的方法。 THXandroid:使用SoundPool播放短暫的演變期短聲音

 public class MainService extends Service implements OnLoadCompleteListener{ 
      private boolean soundradarloaded; 
      private SoundPool spoolradar; 
      private int soundradarID; 
      private Thread timerThread; 
      private boolean timerThreadrunning; 

      public int onStartCommand(Intent intent, int flags, int startId) { 
       soundradarloaded=false; 
       spoolradar = new SoundPool(10, AudioManager.STREAM_MUSIC, 0); 
       soundradarID = spoolradar.load(this, R.raw.beepradar1, 1); 
       spoolradar.setOnLoadCompleteListener(this); 
       timerThreadrunning=true; 
       timerThread=new Thread(new Runnable() { 
       @Override 
       public void run() { 


        int counter=0; 
        long offset=System.currentTimeMillis(); 
        while(timerThreadrunning) { 
         // Traitement 
         longtime=System.currentTimeMillis()-offset; 
         if(soundradarloaded && longtime%400==0){//play every 400ms 
          spoolradar.play(soundradarID, 1, 1, 1, 0, 1f); 
         } 
         try { 
          Thread.sleep(1); 
         } catch (InterruptedException ex) { 
         } 
        } 

        } 
      }); 

      timerThread.start(); 
     } 

    @Override 
    public void onLoadComplete(SoundPool arg0, int arg1, int arg2) { 

       if(arg0==spoolradar) 
        soundradarloaded=true; 

    } 
    @Override 
    public void onStop() { 
     timerThreadrunning=false; 
     try{ 
       Thread.sleep(1); 
      }catch (InterruptedException ex) { 
         } 
     spoolradar.release(soundradarID); 
     } 

} 

回答

0

Thread.sleep()的精確度無法保證。如果了Thread.sleep被忽略(1),然後線

if(soundradarloaded && longtime%400==0){//play every 400ms

可以由相同毫秒期間被執行多次和多個音頻數據流被(後或在不希望的時間)使用了在幾乎相同的時間。第二個問題是TimerThread正在運行並且一直在使用CPU(和電池)。

請參閱https://developer.android.com/reference/java/util/Timer.html或者https://developer.android.com/reference/java/util/concurrent/ScheduledThreadPoolExecutor.html以獲得更好的解決方案。