我尝试编写一个简单的应用程序,每隔X毫秒发出一声蜂鸣声。 有2个按钮可以增加和减少X(向上将执行++ X,向下将执行-X)
当我尝试设置重复声音的时间时,我无法设置X时间。
当我开始'计划'5秒钟(5000毫秒)时,我总是每隔1秒钟发出一声嘟嘟声 - 我根本无法设置间隔时间。
为什么我在间隔设定时间内保持失败?
代码:
private long _valueToDisplay = 5000;
private Timer _timeTimeToBeep;
private TimerTask _task;
private Thread _thread;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_timeTimeToBeep = new Timer();
_task = new TimerTask() {
@Override
public void run() {
_thread = new Thread(new Runnable() {
@Override
public void run() {
playSound();
}
});
_thread.start();
}
};
}
public void playSound(){
final ToneGenerator toneGenerator = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
toneGenerator.startTone(ToneGenerator.TONE_PROP_BEEP);
}
public void startPlayClickBtn(View view) throws InterruptedException {
//_timeTimeToBeep.schedule(_task, 3000, 3000);
_timeTimeToBeep.schedule(_task, 0, _valueToDisplay);
}
答案 0 :(得分:1)
更改您的代码:
private long _valueToDisplay = 1000;
private Timer _timeTimeToBeep;
private TimerTask _task;
private Thread _thread;
final ToneGenerator toneGenerator = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_eep);
_timeTimeToBeep = new Timer();
_task = new TimerTask() {
@Override
public void run() {
_thread = new Thread(new Runnable() {
@Override
public void run() {
playSound();
}
});
_thread.start();
}
};
}
public void playSound(){
toneGenerator.startTone(ToneGenerator.TONE_PROP_BEEP);
}
public void startPlayClickBtn(View view) throws InterruptedException {
//_timeTimeToBeep.schedule(_task, 3000, 3000);
_timeTimeToBeep.schedule(_task, 0, _valueToDisplay);
}
我所做的就是创建一个恒定的ToneGenerator对象。在您的代码中,您每5秒钟创建一个ToneGenerator的新对象。这就是为什么你得到错误。这里创建了一个对象,并在整个程序中使用它。