atm 我的实际 Android 应用程序有问题。
解释:
起初我想在 TextView Char 中按 Char 显示文本。这是我的实际代码
tvIntro.setText("");
final Handler textHandler = new Handler();
for(int i=0; i<intro.length();i++){
final int finalCount = i;
textHandler.postDelayed(new Runnable() {
@Override
public void run() {
tvIntro.setText(tvIntro.getText() + (intro.charAt(finalCount)+""));
}
}, 150 * i);
}
显示整个文本后,我想播放一个声音并连续改变屏幕颜色 5 秒。为此,我的代码是:
myBackground.setBackgroundColor(Color.RED);// set initial colour
final Thread blink = new Thread(new Runnable() {
public void run() {
while (getRunning()) {
try {
Thread.sleep(100);
if(start[0] !=1){
mp.start();
start[0] = 1;
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
updateColor(myBackground);
whichColor = !whichColor;
}
}
});
private void updateColor(final RelativeLayout myBackground) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (whichColor)
myBackground.setBackgroundColor(Color.RED);
else
myBackground.setBackgroundColor(Color.GREEN);
}
});
}
所有功能都在工作,但我也想在执行第二个处理程序之前完成第一个处理程序。此外,第二个处理程序应在 x 秒后停止。
我在理解处理程序和线程的工作方式时遇到了一些问题。 如果有人能为我提供解决方案,那就太好了。
最佳答案
要延迟执行任务直到指定线程(或多个线程)完成,请在您希望等待的线程之后立即添加此行:
myThread.join();
然后在它完成后立即跟进您希望运行的代码。
对于第二个问题,您可以将一个变量设置为您希望在结束线程之前等待的时间量的值(以毫秒为单位),然后将该值减少 100(或您选择告诉的任何数量)每次代码运行时它都会 hibernate )。检查该值是否小于或等于零,然后如果该条件返回 true,则以中断结束线程。所以基本上:
long timeToRun = 5000, sleepTime = 100;
// Your code here...
Thread.sleep(sleepTime);
timeToRun -= sleepTime;
if(timeToRun <= 0) {
myThread.interrupt();
}
可能有更优雅的方法来完成此操作,但至少这应该可以解决您的问题。
关于java - 先后在Android中运行Handler Task,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34522020/