我正在尝试为我的吉他练习制作一个应用程序,在一项活动中同时发生两件事-节拍器和倒数计时器。尽管节拍器更为重要,但两者都需要准确的时间。我已经将ScheduledThreadPoolExecutor用于节拍器:
public void startMetronome() {
if (tempo > 0){
mainExecutor = new ScheduledThreadPoolExecutor(1);
t = mainExecutor.scheduleAtFixedRate(new MyTask(), 0, MILLIS_IN_MINUTE / tempo, TimeUnit.MILLISECONDS);
}
}
class MyTask implements Runnable {
@Override
public void run() {
playSound();
}
}
private void playSound() {
mp = MediaPlayer.create(this, R.raw.metronome);
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
};
});
}
还有一个简单的倒数计时器CountDownTimer:
public void startCounting(int minutes, int seconds){
mainCountDown = new CountDownTimer((minutes * 60 + seconds) * 1000, 1000) {
public void onTick(long millisUntilFinished) {
mMinutes = (int) TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished);
mSeconds = (int) (TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));
CountDownView.setText(""+String.format("%d:%02d", mMinutes, mSeconds));
}
public void onFinish() {
startCountDown.setText("START");
}
}.start();
}
与我的计算机上的Ableton节拍器进行测试之后,即使没有与该应用程序进行任何交互,该应用程序的节拍器(正在运行倒计时)也变得滞后。另一方面,倒数计时已关闭,运作正常。为这两项任务提供合理准确的解决方案的最佳方法是什么?