我想实现一种我们可以在汽车上找到的雷达来帮助停车。在通过活页夹正确连接到我的活动的服务上,我启动了一个线程,该线程必须重复一个短的 sound.wav(110 毫秒长),并且会在短时间内发生变化。使用此代码,在开始第一个循环播放声音但有困难并很快失去节奏。最糟糕的是,服务永远不会停止。垃圾收集器已饱和。我没有找到正确实现这一点的方法。谢谢
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);
}
}