每 X 秒运行一次 backgound 线程(Android Studio)



我有一个代码,它播放 5 个声音,声音之间有 1 秒的延迟,我希望这部分代码每 5 秒执行一次(所以只要布尔变量为真,它将连续运行,当它变为假时,胎面运行停止 - 我有一个按钮来启动和停止此执行(。一切正常,但问题是我无法摆脱第一次单击按钮时的 5 秒延迟,因此当我第一次单击时,声音仅在 5 秒后乞求。我怎样才能让它立即开始,并且只有在第一次开始延迟之后才开始?

这是按钮点击代码:

public void clickHandlerStartTempo(final View view) {
if (!tempoOn) {
Toast toast = Toast.makeText(getApplicationContext(), "Start Tempo!", Toast
.LENGTH_SHORT);
toast.show();
tempoOn = true;
final Handler handler = new Handler();
final int delay = 5000; //milliseconds
handler.postDelayed(new Runnable() {
public void run() {
if (tempoOn) {
runCode(view);
handler.postDelayed(this, delay);
}
}
}, delay);
} else {
Toast toast = Toast.makeText(getApplicationContext(), "Stop Tempo!", Toast
.LENGTH_SHORT);
toast.show();
tempoOn = false;
}
}

下面是运行代码方法:

public void runCode(View view) {
Runnable runnable = new Runnable() {
@Override
public void run() {
playSound(0);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 4; i++) {
if (tempoOn) {
playSound(1);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
return;
}
}
}
};
Thread thread = new Thread(runnable);
Log.i(TAG, "runCode: Thread id = " + thread.getId());
thread.start();
}

我是安卓开发的新手,任何帮助将不胜感激。 谢谢。

首先,您需要在没有线程的情况下播放声音,然后在 4 次计数后执行铰孔 5 秒逻辑停止线程。

public void onStartPress(){
playSound();
someMethod();
}
public void someMethod(){
Handler uiHandler = new Handler(Looper.getMainLooper());
uiHandler.postDelayed(new Runnable() {
@Override
public void run() {
playSound();
someMethod();
}
},1000);
}

不要使用实际的Threads,除非你真的想在 Ui 线程之外做一些事情。大多数情况下,您确实希望将内容保留在 Ui 线程上。

对于简单的重复任务,您可以轻松地重新调整CountDownTimer类的用途。 通常具有(几乎(无限的运行时间或Long.MAX_VALUE(2.92亿年(。拳头onTick在启动后立即发生。

private CountDownTimer mTimer;
private void start() {
if (mTimer == null) {
mTimer = new CountDownTimer(Long.MAX_VALUE, 5000) {
@Override
public void onTick(long millisUntilFinished) {
// start a beeping countdown
new CountDownTimer(5000, 1000) {
private int state = 1;
@Override
public void onTick(long millisUntilFinished) {
playSound(state);
state = state + 1 % 2;
}
@Override
public void onFinish() {
playSound(0);
}
}.start();
}
@Override
public void onFinish() { /* ignore, never happens */ }
};
mTimer.start();
}
}
private void stop() {
if (mTimer != null) {
mTimer.cancel();
mTimer = null;
}
}

最新更新